Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigureWebHost() is not supported by WebApplicationBuilder.Host. Use the WebApplication returned by WebApplicationBuilder.Build() instead" error

Tags:

c#

.net

I have just upgraded a dotnet core 3 api application to a 6.

So before, I had a startup.cs file with a ConfigureServices and a Configure method.

In order to not accidently break anything, and also perhaps save myself from doing work, I wanted to keep the startup.cs file.

So where I before used createdefaultbuilder, like this:

    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
    }

But now, I need to call "createBuilder" instead, and now my program.cs looks like this, where I try to use startup.cs by calling "ConfigureWebHostDefaults" on the host instead.

    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static WebApplicationBuilder CreateHostBuilder(string[] args)
    {
        var webApplicationOptions = new WebApplicationOptions() { ContentRootPath = AppContext.BaseDirectory, Args = args, ApplicationName = System.Diagnostics.Process.GetCurrentProcess().ProcessName };
        var builder = WebApplication.CreateBuilder(webApplicationOptions);
        
        builder.Host.ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
        builder.Host.UseWindowsService();

        return builder;
    }

However, when I try to build and run, the "ConfigureWebHostDefaults", this error comes back at me:

ConfigureWebHost() is not supported by WebApplicationBuilder.Host. Use the WebApplication returned by WebApplicationBuilder.Build() instead.'

Which seems like a pretty obvious instruciton, I just need to call "ConfigureWebHostsDefaults" on the built "WebApplicationBuilder".

But "WebApplication" has no definition for anything called "ConfigureWebHostDefaults", "Usestartup" or a field called "Host"

So it's entirely unclear to me what the error is trying to tell me.

Can someone help me out?

like image 244
penstiaGarse Avatar asked Apr 01 '26 18:04

penstiaGarse


1 Answers

In case you are trying to configure Kestrel in ConfigureWebHostDefaults, it can be done through builder.WebHost.ConfigureKestrel instead, this won't throw an error:

builder.WebHost.ConfigureKestrel(serverOptions =>
{
   serverOptions.Listen(System.Net.IPAddress.Any, 44380, listenOptions =>
   {
       listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
       listenOptions.UseHttps("self.pfx", "123qwe");
   });
});
like image 167
SzilardD Avatar answered Apr 03 '26 06:04

SzilardD