In .NET Core 2 Web API app, I could override configuration urls using appsettings.json, but in the official docs they introduced extra file "hosting.json", Why? What's the point of adding complexity?
Below code is fully working using appsettings.json:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) //see Side note below
.AddJsonFile("appsettings.json", optional: true)
.AddCommandLine(args)
.Build();
return WebHost.CreateDefaultBuilder(args)
.UseConfiguration(config)
.UseStartup<Startup>()
.Build();
}
}
appsettings.json content:
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"urls": "http://*:5005/"
}
Side note:
Commenting .SetBasePath(Directory.GetCurrentDirectory()) will keep VS 2017 debug mode operational (means apply launchSettings.json, and auto launch url) otherwise it won't. I guess its related to the CreateDefaultBuilder implementation.
I think, hosting.json is a configuration file used specifically for asp.net core application hosting. (if you know more about hosting)
WebHostBuilder directly maps its keys with the hosting.json file and it doesn't have the capability to load the config section as we do in normal configuration settings.
According to link attached in your post
Use Configuration to configure the host. In the following example,
host configuration is optionally specified in a hosting.json file. Any
configuration loaded from the hosting.json file may be overridden by
command-line arguments.
If only we explicitly us hosting.json then the WebHostBuilder configurations can be modified using dotnet command.
for example
dotnet run --urls "http://*:8080"
this will override the urls from hostings.json file.
Hopefully, this may give some idea.
PC: hosting.json can be renamed like myappsettings.json it can
have configuration and Web Host Builder configuration.
Related
The function app runs locally but is deployed as a Linux container. The deployed function isn't reporting any issues in the portal and I can see the three functions listed in the Functions blade. However, none are working (one is a simple HTTP ping which is returning a 502 Bad Gateway response).
So no obvious issues in the portal, but inspection of logs reveals this recurring exception:
System.Threading.Tasks.TaskCanceledException at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess
The formatted message is:
Failed to start a new language worker for runtime: dotnet-isolated
My suspicion is that this is something to do with the value of the site setting linuxFxVersion. Mind you, I've tried using DOTNET|6.0 and DOTNET-ISOLATED|6.0. In both cases it doesn't seem to make a difference and anyway when I export the function app's ARM template it has linuxFxVersion set to the URI of the container image prefixed with DOCKER|.
That seems to relate to this specific advice from Microsoft about pinning the host version on Linux. But it still isn't clear to me which value I should us, and anyway, in another place the advice from another Microsoft document states:
To support zip deployment and running from the deployment package on Linux, you also need to update the linuxFxVersion site config setting to DOTNET-ISOLATED|6.0.
Anyway, Here are the details of my config. I've followed every bit of guidance from Microsoft so I hope someone can spot what I've missed...
First two parts of project file:
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>V4</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
<ImplicitUsings>true</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.CosmosDB" Version="3.0.9" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.3.0" OutputItemType="Analyzer" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.5.2" />
</ItemGroup>
host.json:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
}
}
Main method in Program.cs:
public static async Task Main()
{
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureAppConfiguration((context, configurationBuilder) =>
{
configurationBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
if (context.HostingEnvironment.IsDevelopment())
{
configurationBuilder.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
}
else
{
configurationBuilder.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
}
configurationBuilder.AddEnvironmentVariables();
})
.ConfigureServices((context, collection) => ConfigureServices(collection, context.Configuration, context.HostingEnvironment))
.Build()
.RunAsync();
}
The function provisioning pipeline sets the following app settings:
FUNCTIONS_EXTENSION_VERSION: '~4'
FUNCTIONS_WORKER_RUNTIME: 'dotnet-isolated'
As stated above, the latest version of my site config defined during provisioning includes this:
linuxFxVersion: 'DOTNET-ISOLATED|6.0'
The Docker image uses mcr.microsoft.com/azure-functions/dotnet-isolated:4 as a base image for the published app, and mcr.microsoft.com/dotnet/sdk:6.0 to build it.
Please tell me there's something obvious I'm missing. We currently have two function apps, and neither can be deployed as dotnet-isolated. It's driving me mad!
The exception what you saw is not directly from your application, instead it is a general exception without detaills from an Azure Function runtime-process - so it's useless.
The reasons can be anything, for example: forget to await on a task.
public static async Task Main()
{
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureAppConfiguration(builder =>
{
builder
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
.Build();
})
.ConfigureServices((context, collection) => ConfigureServices(collection, context.Configuration, context.HostingEnvironment))
.Build();
host.RunAsync(); // await host.RunAsync();
}
Or a corrupted appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft": "Warning",
"Host": "Warning",
"Function": "Information",
"Host.Aggregator": "Information"
}
}
Or a missing configure call during startup.
public static async Task Main()
{
var host = new HostBuilder()
// .ConfigureFunctionsWorkerDefaults()
.ConfigureAppConfiguration(builder =>
{
builder
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
.Build();
}))
.ConfigureServices((context, collection) => ConfigureServices(collection, context.Configuration, context.HostingEnvironment))
.Build();
await host.RunAsync();
}
That runtime-process from Microsoft which launches your application captures all your console logs and trashes them in case of exceptions during its own startup.
Btw, you should also enable Code Analysis which is per default not enabled in .net 6.
After battling with this for 2 days I decide to strip right down to the bare bones. Followed the Microsoft guide from scratch. This led me to identify the following line as the problem:
configurationBuilder.AddEnvironmentVariables();
As soon as I add this line to my Program and push a new image to the function app, everything breaks upon restart. However, there's no indication as to why. The Docker logs exposed by Kudo report this as the final entry:
2022-05-18T14:06:46.295Z INFO - Container [image-name] for site [function-name] initialized successfully and is ready to serve requests.
App Insights traces indicate that an exception has occurred at line 52 of Program.cs, which is my host.Run(); line.
The exception itself is:
System.InvalidOperationException at Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcFunctionInvocationDispatcherLoadBalancer.GetLanguageWorkerChannel
And there's a message hidden in there saying "Did not find any initialized language workers" which I understand is Azure Function language for "something bad happened during startup but I'm not going to tell you what or why".
So this at least explains why my function wasn't running, and hopefully my experience will save someone else time in the future, but since my app depends on configuration added to the function by a pipeline I still don't have a working app. For that I will ask a new question and link it here...
Update
Here is the follow up question, which I've already answered!
I have the following code in my console application.
// Build configuration
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(ApplicationInfo.DataPath)
.AddJsonFile("appsettings.json", false, false)
.Build();
// Configure Serilog
string logFormat = "[{Timestamp:yyyy-MM-dd hh:mm:ss tt}][{Level:u3}] {Message:lj}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.WriteTo.Console(LogEventLevel.Verbose, logFormat)
.WriteTo.File(ApplicationInfo.GetDataFileName("log"), LogEventLevel.Verbose, logFormat)
.CreateLogger();
AppHost = Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureServices((context, services) =>
{
services.AddDbContext<TTApplicationDbContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
});
services.Configure<EmailSettings>(configuration.GetSection("EmailSettings"));
services.Configure<SftpSettings>(configuration.GetSection("FtpSettings"));
})
.Build();
This seems to be working. However, when I add the following section to my appsettings.json file, I do not get any of the verbose logging from within the framework. All I get is the logging that I specifically log in my application.
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"System": "Information"
}
}
}
As best I can tell, Serilog is ignoring these settings. How can I change that?
Update:
If I change the Default value to Debug in appsettings.json, that does in fact control whether or not my own calls to LogDebug() show up. But I don't understand why none of Microsoft's logging shows up. Wouldn't Microsoft's code use whatever logger is configured?
While configuring a DotNet Core App, I had the same problem. I found that if I added the Nuget Package serilog-extensions-hosting, it will also start outputting the framework messages to the logs.
https://github.com/serilog/serilog-extensions-hosting
I hope this helps
I am using NET5 ASP.NET MVC application. Application is using Serilog.AspNetCore 3.4.0 for logging
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Error"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console"],
"WriteTo": [
{
"Name": "Console"
}
]
}
}
Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
})
.UseSerilog((hostingContext, logging) =>
{
logging.ReadFrom.Configuration(hostingContext.Configuration);
});
});
I have also tried
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(hostingContext.Configuration)
.CreateLogger();
logging.AddSerilog();
});
});
Issue
My expectation is no Information log will be shown in Console since default LogLevel is Error.
However, that is not working. In console I see every request is getting logged including Information
Throughout my application I am using Microsoft.Extensions.Logging.ILogger<MyClassName> to log information. All those statements are actually logging Info even if the LogLevel is Error.
Looks like Serilog ignoring LogLevel from Microsoft.Extensions.Logging.
Note that, I can set serilog's restrictedToMinimumLevel property to Error and that stops logging information. However I think serilog should obey the LogLevel from Microsoft.Extension.Logging
Use MinimumLevel property:
"Logging": {
"MinimumLevel": {
"Default": "Error"
}
}
Also it supports overrides for categories:
"Logging": {
"MinimumLevel": {
"Default": "Error",
"Override": {
"System": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore": "Debug"
}
}
}
If you check the project's Github page it advises to actually remove the standard "Logging" section in appsettings.json :-(
I think this is bad since it actually breaks the compatibility with Microsoft.Extensions.Logging framework (you can't anymore change the actual log provider (Log4Net, NLog, Serilog) without changing the appsettings.json).
If you use Serilog.Extensions.Logging and AddSerilog() on ILoggingBuilder, you'll get what you're expecting.
However, IHostBuilder.UseSerilog() (provided by Serilog.Extensions.Hosting, via Serilog.AspNetCore) is almost always a better choice, hence that's what all the Serilog docs show.
Although it seems more "integrated" to use the default configuration section this way, what you're getting behind the scenes is actually two different logging frameworks running at the same time, e.g. in the AddSerilog() case (or in the default NLog configuration):
ILogger<T> -->
MEL (routing, configuration, levels, filters) -->
Serilog (routing, configuration, levels, filters)
Logging is supposed to be very predictable/reliable and lightweight. Having two logging frameworks running at the same time erodes this and creates problems where the levels and filters specified for one framework don't match the other. (E.g. Debug and trace logs not printed when using Nlog and ILoggerFactory in .NetCore console app).
In the UseSerilog() case, (and when NLog's ReplaceLoggerFactory option is specified - mentioned in a comment on the SO thread above), you get:
ILogger<T> -->
Serilog (routing, configuration, levels, filters)
You give up support for the default "Logging" configuration section, but in exchange, you get rid of a whole logging framework at runtime, and all of your Serilog (or NLog) configuration just works, with the Microsoft.Extensions.Logging ILogger<T> available to your application code and the framework.
I'm trying to deploy a .NET Core 2.1 application to an Azure Service App. I'm able to run my solution locally successfully, but when I deploy the application out to Azure Service Apps, I begin to get the following error when I call dotnet /home/site/wwwroot/MyApplication.dll on the application.
Unhandled Exception: System.ArgumentNullException: String reference not set to an instance of a String.
Parameter name: s
at System.Text.Encoding.GetBytes(String s)
at MyApplication.Startup.ConfigureServices(IServiceCollection services) in /home/vsts/work/1/s/MyApplication/Startup.cs:line 51
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at MyApplication.Program.Main(String[] args) in /home/vsts/work/1/s/MyApplication/Program.cs:line 23
at MyApplication.Program.<Main>(String[] args)
bash: line 1: 1096 Aborted (core dumped) dotnet /home/site/wwwroot/MyApplication/MyApplication.dll
This appears that I have a null reference on line 51 of my Startup.cs method, inside the ConfigureServices method. This correlates to the line where I build my configuration, using _configuration = builder.Build()
public IConfiguration _configuration { get; set; }
public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
_configuration = configuration;
_hostingEnvironment = hostingEnvironment;
}
public void ConfigureServices(IServiceCollection services)
{
var builder = new ConfigurationBuilder()
.SetBasePath(_hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
_configuration = builder.Build(); // this is line 51
var appSettingsSection = _configuration.GetSection("AppSettings");
...
}
Which the only thing that I can think of would be my appsettings.json transformation. In dev, I point to my dev server, in prod, I point to production. So after the build, I have a file transformation set up to make this change.
However, I've pulled the generated appsettings.json from the App Service, inserted it into my local appsettings.json, and it still compiles and runs just fine.
Here's the appsettings.json that is getting deployed. It's the exact same, except for the name of the server and username/password strings.
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AppSettings": {
"SecretKey": "MySecretKey",
"SuperAdminEmail": "myemail#domain.com"
},
"ConnectionStrings": {
"AuthDatabase": "Server=prod.mydomain.com;Database=Authentication;User Id=myUser;Password=Password1!;TrustServerCertificate=true"
},
"AllowedHosts": "*"
}
I can't see what would be causing this. I tried deploying this to an AWS Lightsail Ubuntu 18.04 instance to see if that works. I got the same error sometimes, however, after enough tries of killing the service, rebooting the server, and other items, I got it to run for 10 minutes, before it crashed again.
I'm not great with logging, especially on Azure App Services... how can I go about tracking down WHAT string is null, and what I can do to verify that it has any necessary values?
As you mentioned in the comments, the value of _hostingEnvironment.ContentrootPath on the AppService is '/home' and this is the issue as your application is not able to read something due to the wrong path referred by the AppService.
You can change your ContentRootPath by following this SO post and accordingly choose the approach as per your requirements.
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?
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.
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();
}
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.
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.
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.
Change the port Number in json file
Use following one line of code .UseUrls("http://*:80") in Program.csThus changing .UseStartup<Startup>() to.UseStartup<Startup>()
.UseUrls("http://*:80")
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"));
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
will clients from other machine be able to access the service?
add to appsettings.json
"Urls": "http://0.0.0.0:8082",
All the other answer accounts only for http URLs. If the URL is https, then do as follows,
Open launchsettings.json under Properties of the API project.
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"
}
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:
There you can enter a custom URL:port for ASPNETCORE_URLS like this:
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.
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
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();
});
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:
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
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");
});
});
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.
In asp.net core 6
app.Run("https://*:25565");
or in my case for deploying on heroku
app.Run("https://*:"+Environment.GetEnvironmentVariable("PORT"));
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")