Override Default port and Host Name Used By ASP.NET Core Toolset

.NET Core is the brand new modular framework from Microsoft for creating a wide variety of applications targeting Windows, Web, Cloud, IoT devices etc. Along with that they have introduced a cross platform toolchain for the command line which will help you to create and execute .NET core apps from the command line. 

So for creating a normal web app in the .NET Core we will execute the following command.

> dotnet run -t Web

Then you will restore the packages by executing the command given below

> dotnet restore

After that you will execute the run command to build and host the application locally

> dotnet run

When this command is executed, it will first compile the application and upon successful build it will then host it using the built-in web server named Kestrel. Kestrel will use the port number 5000 by default for listening the requests for your app.

From the screenshot you can see that the app is using port #5000 and is binded to localhost. This will be perfectly ok in a Dev enviroment since the developer will creating the application and is hosting it in the same machine. But this won't work in a production environment, where the requests to our app will be coming to the server from different machines out in the wild. That means, if you try to access the site using the ip address of the machine instead of localhost you will get a 404 error.

We can overcome this in a variety of ways such as by setting the environment variable ASPNETCORE_URLS, using the UseUrls() method in the startup.cs or by passing the url to the dotnet run command as a parameter. Let's how we can solve this by setting the environment variable.

ASP.NET Core uses the ASPNETCORE_URLS enviromnet variable to specify a custom port as well as a different hostname for your web application. Here, while setting the variable I have used a plus(+) sign to indicate that the hostname can be an ip address or machine name and the number indicates after the colon is the port on which the request will be connected to. Also, you can use any symbol instead of + such as * which is the most commonly used one.

 

Now if you execute the dotnet run command, you will see that it is using 5051 as the port for listening the requests and the hostname is showing a +

  

If your try to access the site using the IP address followed by the port # we specified while setting the environment variable, you will be able to browse the site as shown below.


No Comments

Add a Comment