How to specify the port an ASP.NET Core application is hosted on?
In ASP.NET Core 3.1, there are 4 main ways to specify a custom port:
- Using command line arguments, by starting your .NET application with
--urls=[url]
:
dotnet run --urls=http://localhost:5001/
- Using
appsettings.json
, by adding aUrls
node:
{
"Urls": "http://localhost:5001"
}
- Using environment variables, with
ASPNETCORE_URLS=http://localhost:5001/
. - Using
UseUrls()
, if you prefer doing it programmatically:
public static class Program
{
public static void Main(string[] args) =>
CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(builder =>
{
builder.UseStartup<Startup>();
builder.UseUrls("http://localhost:5001/");
});
}
Or, if you're still using the web host builder instead of the generic host builder:
public class Program
{
public static void Main(string[] args) =>
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://localhost:5001/")
.Build()
.Run();
}
You can insert Kestrel section in asp.net core 2.1+ appsettings.json file.
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://0.0.0.0:5002"
}
}
},
if you have not kestrel section,you can use "urls":
{
"urls":"http://*.6001;https://*.6002"
}
but if you have kestrel in appsettings.json, urls section will failure.