[c#] How to change the port number for Asp.Net core app?

I added the following section in project.json.

  "commands": {
    "run": "run server.urls=http://localhost:8082",
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:8082",
    "weblistener": "Microsoft.AspNet.Hosting --server WebListener --server.urls http://localhost:8082"
  },

However, it still shows "Now listening on: http://localhost:5000" when run it using dotnet myapp.dll?

BTW, will clients from other machine be able to access the service?

This question is related to c# asp.net-core .net-core

The answer is


Yes this will be accesible from other machines if you bind on any external IP address. For example binding to http://*:80 . Note that binding to http://localhost:80 will only bind on 127.0.0.1 interface and therefore will not be accesible from other machines.

Visual Studio is overriding your port. You can change VS port editing this file Properties\launchSettings.json or else set it by code:

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://*:80") // <-----
            .Build();

        host.Run();

A step by step guide using an external config file is available here.


In visual studio 2017 we can change the port number from LaunchSetting.json

In Properties-> LaunchSettings.json.

Open LaunchSettings.json and change the Port Number.

Launch

Change the port Number in json file

enter image description here


In Asp.net core 2.0 WebApp, if you are using visual studio search LaunchSettings.json. I am adding my LaunchSettings.json, you can change port no as u can see.

enter image description here


you can also code like this

        IConfiguration config  = new ConfigurationBuilder()
        .AddCommandLine(args)
        .Build(); 
        var host = new WebHostBuilder()
         .UseConfiguration(config)
         .UseKestrel()
         .UseContentRoot(Directory.GetCurrentDirectory()) 
         .UseStartup<Startup>()
         .Build();

and set up your application by command line :dotnet run --server.urls http://*:5555


Maybe it's because I am not using Core yet. My project didn't have a LaunchSettings.json file but that did prompt me to look in the project properties. I found it under the Web tab and simply changed the project url: enter image description here


Go to your program.cs file add UseUrs method to set your url, make sure you don't use a reserved url or port

 public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()

                // params string[] urls
                .UseUrls(urls: "http://localhost:10000")

                .Build();
    }

We can use this command to run our host project via Windows Powershell without IIS and visual studio on a separate port. Default of krestel web server is 5001

$env:ASPNETCORE_URLS="http://localhost:22742" ; dotnet run

Use following one line of code .UseUrls("http://*:80") in Program.cs

Thus changing .UseStartup<Startup>()

to

.UseStartup<Startup>() .UseUrls("http://*:80")


All the other answer accounts only for http URLs. If the URL is https, then do as follows,

  1. Open launchsettings.json under Properties of the API project.

    enter image description here

  2. Change the sslPort under iisSettings -> iisExpress

A sample launchsettings.json will look as follows

{
  "iisSettings": {
    "iisExpress": {
      "applicationUrl": "http://localhost:12345",
      "sslPort": 98765 <== Change_This
    }
  },

in appsetting.json

{ "DebugMode": false, "Urls": "http://localhost:8082" }


3 files have to changed appsettings.json (see the last section - kestrel ), launchsettings.json - applicationurl commented out, and a 2 lines change in Startup.cs

Add below code in appsettings.json file and port to any as you wish.

  },

 "Kestrel": {

   "Endpoints": {

     "Http": {

       "Url": "http://localhost:5003"

     }

   }

 }

 }

Modify Startup.cs with below lines.

using Microsoft.AspNetCore.Server.Kestrel.Core;

services.Configure<KestrelServerOptions>(Configuration.GetSection("Kestrel"));


in your hosting.json replace"Url": "http://localhost:80" by"Url": "http://*:80" and you will be able now access to your application by http://your_local_machine_ip:80 for example http://192.168.1.4:80


If you want to run on a specific port 60535 while developing locally but want to run app on port 80 in stage/prod environment servers, this does it.

Add to environmentVariables section in launchSettings.json

"ASPNETCORE_DEVELOPER_OVERRIDES": "Developer-Overrides",

and then modify Program.cs to

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseKestrel(options =>
                    {
                        var devOverride = Environment.GetEnvironmentVariable("ASPNETCORE_DEVELOPER_OVERRIDES");
                        if (!string.IsNullOrWhiteSpace(devOverride))
                        {
                            options.ListenLocalhost(60535);
                        }
                        else
                        {
                            options.ListenAnyIP(80);
                        }
                    })
                    .UseStartup<Startup>()
                    .UseNLog();                   
                });

It's working to me.

I use Asp.net core 2.2 (this way supported in asp.net core 2.1 and upper version).

add Kestrel section in appsettings.json file. like this:

{
  "Kestrel": {
    "EndPoints": {
      "Http": {
        "Url": "http://localhost:4300"
      }
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

and in Startup.cs:

public Startup(IConfiguration configuration, IHostingEnvironment env)
{
      var builder = new ConfigurationBuilder()
         .SetBasePath(env.ContentRootPath)
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
         .AddEnvironmentVariables();

      Configuration = builder.Build();
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-core

dotnet ef not found in .NET Core 3 How to use Bootstrap 4 in ASP.NET Core ASP.NET Core - Swashbuckle not creating swagger.json file Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 EF Core add-migration Build Failed ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

Examples related to .net-core

dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Assets file project.assets.json not found. Run a NuGet package restore Is ConfigurationManager.AppSettings available in .NET Core 2.0? How to update record using Entity Framework Core? Using app.config in .Net Core EF Core add-migration Build Failed Build .NET Core console application to output an EXE What is the difference between .NET Core and .NET Standard Class Library project types? Where is NuGet.Config file located in Visual Studio project?