7

I'm learning how to work with in ASP.NET Core 2 and I've come across a rather annoying problem. Whenever I run my application, the Kestrel server ignores my endpoint configuration and instead starts listening on a random port. Needless to say, this is not the behavior I expected. When digging through the server logs I also came upon this message:

Overriding endpoints defined in UseKestrel() because PreferHostingUrls is set to true. Binding to address(es) 'http://localhost:<some random port>' instead.

I have so far been unable to find any documentation on this "PreferHostingUrls" setting or how to change it. Does anyone know how i can configure Kestrel to listen on the specified port instead of a random one?

My host configuration looks like this:

WebHost.CreateDefaultBuilder(args)
        .UseConfiguration(config)
        .UseKestrel(
            options =>
            {
                options.Listen(IPAddress.Loopback, 50734);
                options.Listen(IPAddress.Loopback, 44321, listenOptions =>
                {
                    listenOptions.UseHttps("pidea-dev-certificate.pfx", "****************");
                });
            })
        .UseStartup<Startup>()
        .UseIISIntegration()
        .Build();
Exevan
  • 335
  • 1
  • 3
  • 24
  • It's a new feature in 2.0, what happens when you add `.PreferHostingUrls(false)` before or after `UseKestrel() `? – H H Oct 22 '17 at 21:21
  • The docs are [here](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.hostingabstractionswebhostbuilderextensions.preferhostingurls?view=aspnetcore-2.0) and [here](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/hosting?tabs=aspnetcore2x) – H H Oct 22 '17 at 21:23
  • @HenkHolterman The server still overrides my configured endpoints. – Exevan Oct 23 '17 at 09:22

3 Answers3

5

Ok, so it turned out IISExpress was the culprit here.

For some reason, the default build configuration of Visual Studio 2017 starts my app on an IISExpress server, which does not listen to my endpoint configuration. To solve the issue, I simply had to switch to a custom run configuration.

To summary, I just had to switch from this:

enter image description here

to this:

enter image description here

(PIdea being the name of my project)

Exevan
  • 335
  • 1
  • 3
  • 24
4

When I test with .NetCore 3.0, I fail with using different port 5000 in launchSettings.json
This is settings in the file launchSettings.json

"ABC": {
   "commandName": "Project",
   "launchBrowser": true,
   "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    },
    "applicationUrl": "http://localhost:5002"
 }

I think this is the root cause that default host runs with the port 5000 When there is a change, there needs to modify setting.

There are 3 ways to achieve expected result:

  1. Add kestrel settings in appsettings.json and appsettings.Development.json

    "Kestrel": {
      "EndPoints": {
        "Http": {
          "Url": "http://localhost:5002"
        },
        "Https": {
          "Url": "https://localhost:5003"
        }
      }
    },
    
  2. Use Kestrel with registration of listening different port

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args).ConfigureKestrel(serverOptions =>
        {
            // Set properties and call methods on options
            serverOptions.Listen(IPAddress.Loopback, 5002); //Modify port
        })
       .UseKestrel()
       .UseContentRoot(Directory.GetCurrentDirectory())  
       .UseIISIntegration()
       .UseStartup<Startup>();
    

    or modify config in appsettings.json.

    "Host": {  
      "Port": 5002  
    } 
    

    and then call like below

    .ConfigureKestrel(serverOptions =>
        {
            // Set properties and call methods on options
            options.Listen(IPAddress.Loopback, config.GetValue<int>("Host:Port"));
        })
    

    or

    .UseKestrel((context, serverOptions) =>
        {  
            var config = new ConfigurationBuilder()  
               .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: false).Build();  
            options.Listen(IPAddress.Loopback, context.Configuration.GetValue<int>("Host:Port"));  
         }) 
    

    or In Startup.ConfigureServices, load the Kestrel section of configuration into Kestrel's configuration:

     public void ConfigureServices(IServiceCollection services)
     {
          services.Configure<KestrelServerOptions>(
              Configuration.GetSection("Kestrel"));
     }
    
  3. Use UseUrls

     public class Program
     {      
         public static void Main(string[] args)
         {
             CreateHostBuilder(args).Build().Run();
         }
    
         public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(builder =>
             {
                 builder.ConfigureKestrel(serverOptions =>
                     {
                         // Set properties and call methods on options
                     })
                     .UseContentRoot(Directory.GetCurrentDirectory())
                     .UseIISIntegration()
                     .UseUrls("http://localhost:5002")  //Add UseUrl above UseStartup
                     .UseStartup<Startup>();
             });     
          }
      }
    

    or

     public static IWebHostBuilder CreateWebHostBuilder(string[] args)  
     {  
         var config = new ConfigurationBuilder()  
             .SetBasePath(Directory.GetCurrentDirectory())  
             .AddJsonFile("appsettings.json", optional: false)  
             .Build();  
    
         var webHost =  WebHost.CreateDefaultBuilder(args)  
             .UseUrls($"http://localhost:{config.GetValue<int>("Host:Port")}")  
             .UseKestrel()  
             .UseStartup<Startup>();  
    
         return webHost;  
     }  
    
shA.t
  • 16,580
  • 5
  • 54
  • 111
Minh Nguyen Van
  • 109
  • 1
  • 2
3

Add

"Kestrel": {
  "EndPoints": {
    "Http": {
      "Url": "http://localhost:5002"
    },
    "Https": {
      "Url": "https://localhost:5003"
    }
  }
}  

to appsettings.json.

shA.t
  • 16,580
  • 5
  • 54
  • 111
amilamad
  • 470
  • 6
  • 9