ca9163d9
ca9163d9

Reputation: 29247

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 this service?

Upvotes: 135

Views: 327052

Answers (29)

F. Markus
F. Markus

Reputation: 21

In Visual Studio 2022 and .net core 8 using the Properties/launchSettings.json worked best for me.

For dockerized applications this section is generated: enter image description here

Adding httpPort and sslPort worked like a charm:

"Container (Dockerfile)": {
  "commandName": "Docker",
  "launchBrowser": true,
  "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
  "environmentVariables": {
    "ASPNETCORE_HTTP_PORTS": "8080"
  },
  "httpPort": 8082,
  "sslPort": 8083,
  "useSSL": true,
  "publishAllPorts": true
}

Upvotes: 2

kevinc
kevinc

Reputation: 635

Set environment variable ASPNETCORE_HTTP_PORTS=80

Upvotes: 0

Thanawat
Thanawat

Reputation: 389

For .NET 8 the default port changed from 80 to 8080

You can change the default port by using the variable name ASPNETCORE_HTTP_PORTS

Example:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ASPNETCORE_HTTP_PORTS": 80
}

Document ref.: https://learn.microsoft.com/en-us/dotnet/core/compatibility/containers/8.0/aspnet-port

Upvotes: 1

raddevus
raddevus

Reputation: 9087

Here's the solution that worked for me in March 2024, running net8.0 and a minimal webAPI with top-level statements:

At the top of your Program.cs you'll see a line of code something like:

var builder = WebApplication.CreateBuilder(args);

Place the following code after that:

builder.WebHost.ConfigureKestrel((context, serverOptions) =>
{
    // 5270 is the port number
    serverOptions.Listen(System.Net.IPAddress.Loopback, 5270);
});

This started the app on 127.0.0.1:5270.

This allowed me to set up nginx running on Linux to point to this app.

Upvotes: 0

Ashar Ali
Ashar Ali

Reputation: 1

In the new .NET versions without the Startup.cs file you can add line

builder.WebHost.UseUrls("http://localhost:5010", "https://localhost:5011");

after the line

var builder = WebApplication.CreateBuilder(args);

like so

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://localhost:5010", "https://localhost:5011");

and it will change the ports to 5010 and 5011 respectively.

Upvotes: 0

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102458

Building on @Abdus Salam Azad's answer...

In Visual Studio 2022 if you right click an ASP.NET Core Web API project for example, you have access to this UI where you can set up ASPNETCORE variables like this:

enter image description here

There you can enter a custom URL:port for ASPNETCORE_URLS like this:

enter image description here

https://localhost:44777

Upvotes: 13

Marco Montebello
Marco Montebello

Reputation: 1

go to launchsettings.json and change all the ports you can see there, including the ones in the IIS section

Upvotes: 0

Codingwiz
Codingwiz

Reputation: 313

Don't have enough rep to add this as a comment, but I want to add that the WebHost.UseUrls() in .net core 6 can be set using a combination of IPAddress and IPEndPoint in file Program.cs

if (!builder.Environment.IsDevelopment()) // app in release
{
               // listen to any ip on port 80 for http
    IPEndPoint ipEndPointHttp = new IPEndPoint(IPAddress.Any, 80),
           
               // listen to any ip on port 443 for https
               ipEndPointHttps = new IPEndPoint(IPAddress.Any, 443);

    builder.WebHost.UseUrls($"http://{ipEndPointHttp}",
                            $"https://{ipEndPointHttps}");

    // enforce ssl when in release
    builder.Services.AddHsts(options =>
    {
        options.Preload = true;
        options.IncludeSubDomains = true;
        options.MaxAge = TimeSpan.FromDays(3); // a commonly used value is one year.
    });

    // redirect to specific https port
    builder.Services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = (int)HttpStatusCode.PermanentRedirect;
        options.HttpsPort = ipEndPointHttps.Port;
    });
}
else // app in debug
{
               // listen to localhost on port 8081 for http
    IPEndPoint ipEndPointHttp = new IPEndPoint(IPAddress.Loopback, 8081),

               // listen to localhost on port 5001 for https
               ipEndPointHttps = new IPEndPoint(IPAddress.Loopback, 5001);

    builder.WebHost.UseUrls($"http://{ipEndPointHttp}",
                            $"https://{ipEndPointHttps}");

    // redirect to specific https port
    builder.Services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
        options.HttpsPort = ipEndPointHttps.Port;
    });
}

... // rest of configuration

app.UseHttpsRedirection(); // set redirection to https if url is in http

....

Also note that using these values new IPEndPoint(IPAddress.Any, 80), *:80, ::80 are all equivalent, but I prefer IPEndPoint since it is more verbose

If a custom ip address (ex: 192.168.1.200) is needed other than IPAddress.Any or IPAddress.Loopback, a new address can be set using IPAddress.Parse("192.168.1.200")

Upvotes: 0

thran
thran

Reputation: 129

The following works in ASP.Net Core 6.0. Inside Program.cs have this:

var builder = WebApplication.CreateBuilder(args);

if (!app.Environment.IsDevelopment())
{
    builder.WebHost.UseUrls("http://*:80", "https://*.443");
}

I find it is useful to wrap it in a conditional statement when publishing to production, but this isn't necessary.

This works running from a Kestrel server on Mac OS 12.

Upvotes: 5

Rajesh Kumar
Rajesh Kumar

Reputation: 622

Core 6.0 --> Without any JSON setting changes we do some thing like this.. I also commented some code bcoz I don't have certificate. we can run it any port.

 builder.WebHost.ConfigureKestrel((context, serverOptions) =>
            {
               // serverOptions.Listen(System.Net.IPAddress.Loopback, 5003);
                serverOptions.Listen(System.Net.IPAddress.Loopback, 8086, listenOptions =>
            {
                listenOptions.UseHttps();
              //listenOptions.UseHttps("testCert.pfx", "testPassword");
            });
        }); 

Upvotes: 1

Yarden zamir
Yarden zamir

Reputation: 31

In asp.net core 6
app.Run("https://*:25565");
or in my case for deploying on heroku
app.Run("https://*:"+Environment.GetEnvironmentVariable("PORT"));

Upvotes: 2

Max
Max

Reputation: 19

I created my project using Visual Studio 2022, so in Project/Properties/launchSettings.json there are two parts for this topic: 1- for lunching in IISExpress :

"iisSettings": {
..
"iisExpress": {
  "applicationUrl": "http://localhost:31520",
  "sslPort": 44346
}

},

2- for lunching through IDE:

"profiles": {
"MaxTemplate.API": {
  ...
  "applicationUrl": "https://localhost:7141;http://localhost:5141",
  ...
  }
},

For example you can change the port 7141 to 5050 and run the project again.

Upvotes: 0

Craig Miller
Craig Miller

Reputation: 561

I had a similar issue with a Kubernetes deployment after upgrading to .NET 6. The solution was simply to add the following environment variable to the deployment:

- name: Kestrel__Endpoints__Http__Url
  value: http://0.0.0.0:80

This will work anywhere else where you can use an environment variable

Upvotes: 1

Shaybakov
Shaybakov

Reputation: 756

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

add to appsettings.json

  "Urls": "http://0.0.0.0:8082",

Upvotes: 18

Tom Charles Zhang
Tom Charles Zhang

Reputation: 1050

Use simply dotnet YouApp.dll --urls http://0.0.0.0:80.

P.S. I don't know why I need to google this everytime and everytime it doesn't show up. So here it is.

Upvotes: 73

Gerardo Grignoli
Gerardo Grignoli

Reputation: 15217

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://localhost:80") // <-----
            .Build();

        host.Run();

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

Upvotes: 81

AditYa
AditYa

Reputation: 917

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"));

Upvotes: 15

mostafa kazemi
mostafa kazemi

Reputation: 575

in appsetting.json

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

Upvotes: 3

Anthony Griggs
Anthony Griggs

Reputation: 1641

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

Upvotes: 1

HirenP
HirenP

Reputation: 121

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();                   
                });

Upvotes: 1

Amara Miloudi
Amara Miloudi

Reputation: 140

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

Upvotes: 0

Kolappan N
Kolappan N

Reputation: 4011

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
    }
  },

Upvotes: 6

AminRostami
AminRostami

Reputation: 2772

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();
}

Upvotes: 77

Akshay Vijay Jain
Akshay Vijay Jain

Reputation: 16025

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

Thus changing .UseStartup<Startup>()

to

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

Upvotes: 16

Eyayu Tefera
Eyayu Tefera

Reputation: 941

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();
    }

Upvotes: 10

Sathish
Sathish

Reputation: 2099

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

Upvotes: 20

Abdus Salam Azad
Abdus Salam Azad

Reputation: 5512

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

Upvotes: 11

GirishBabuC
GirishBabuC

Reputation: 1379

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

Upvotes: 33

liam
liam

Reputation: 29

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

Upvotes: 1

Related Questions