How to Specify the Port for Hosting an ASP.NET Core Application
By FoxLearn 12/5/2024 12:18:35 PM 175
To specify the port using appsettings.json
, you can add a Urls
node under the Kestrel
section.
Open or create the appsettings.json
file in your ASP.NET Core project, then add a Kestrel
section and specify the desired URL under the Endpoints
node.
{ "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:5000" } } } }
In this example, the application will be hosted on http://localhost:5000
. This method allows you to centralize the configuration for the server and port in the appsettings.json
file.
The launchSettings.json
file is used to configure how the application starts in different environments (e.g., Development, Production).
Open the Properties\launchSettings.json
file in your project, then modify the applicationUrl
setting under the profiles
section.
{ "profiles": { "IIS Express": { "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "http://localhost:5001" }, "ProjectName": { "commandName": "Project", "applicationUrl": "http://localhost:5002", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
In this example, the application will run on http://localhost:5002
.
You can set the port directly in the Program.cs
file using the UseUrls
method.
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseUrls("http://localhost:5003"); // Specify the port here webBuilder.UseStartup<Startup>(); }); }
To specify the port programmatically, you can use the UseUrls()
method in the Program.cs
file of your ASP.NET Core application. This method allows you to set the URL that the application should listen on.
You can set the port using the ASPNETCORE_URLS
environment variable. This is helpful when running the application on a server or when deploying.
On Windows (Command Prompt):
set ASPNETCORE_URLS=http://localhost:5004
On Linux/macOS:
export ASPNETCORE_URLS=http://localhost:5004
You can specify the port when running the application from the command line by passing the --urls
argument.
dotnet run --urls "http://localhost:5005"
If you're running the application inside a Docker container, you can expose the port using the -p
flag when running the container.
docker run -p 5006:80 your_image_name
This will map port 5006 on your machine to port 80 in the Docker container.