Can I set listen URLs in appsettings.json in ASP.n

2019-02-13 11:27发布

I'm creating an ASP.net Core 2.0 app to run on the .net Core 2.0 runtime, both currently in their Preview versions. However, I cannot figure out how to have Kestrel use something other than the default http://localhost:5000 listen URL.

Most documentation that I could Google talks about a server.urls setting, which seems to have been changed even in 1.0-preview to just be urls, however neither works (turning on Debug logging has Kestrel telling me that no listen endpoints are configured).

A lot of documentation also talks about a hosting.json and that I can't use the default appsettings.json. However, if I compare the recommended approach of loading a new config, this looks pretty much exactly like what the new WebHost.CreateDefaultBuilder method does, except that it loads appsettings.json.

I currently don't understand how appsettings.json and IConfigureOptions<T> are related, if at all, so it's possible that my trouble stems from a lack of understanding of what KestrelServerOptionsSetup actually does.

4条回答
该账号已被封号
2楼-- · 2019-02-13 11:55

I got it working with this

public static IWebHost BuildWebHost(string[] args) => 
        WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("hosting.json", optional: true)
                .Build()
            )
            .UseStartup<Startup>()
            .Build();

And the hosting.json

{ "urls": "http://*:5005;" }
查看更多
欢心
3楼-- · 2019-02-13 11:58

Works for me as it used to be

WebHost.CreateDefaultBuilder(args)
    .UseConfiguration( new ConfigurationBuilder().AddCommandLine(args).Build() )
    .UseStartup<Startup>()
    .Build();

Then

dotnet myapp.dll --urls "http://*:5060;"
查看更多
姐就是有狂的资本
4楼-- · 2019-02-13 12:02

To set listen URLs in appsettings.json, add "Kestrel" section:

"Kestrel": {
    "EndPoints": {
        "Http": {
            "Url": "http://localhost:5000"
        }
    }
}

Reference: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.2

查看更多
走好不送
5楼-- · 2019-02-13 12:12

None of the above worked for me. This one worked for me:

public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
            .UseKestrel(options =>
            {
                options.Listen(System.Net.IPAddress.Loopback, 44306, listenOptions =>
                {
                    listenOptions.UseHttps("mysertificate.pfx", "thecertificatePassword");
                });
            })
        .Build();

(Change the 44306 to a port of your own liking)

And there might be a lot of help in this StackOverflow answer

查看更多
登录 后发表回答