Reputation: 5070
I have REST API application created using ASP.NET Core 2.1. REST API is created by WebHostBuilder and hosted by Kestrel.
Startup.Kernel = kernel;
_restApiServer = new WebHostBuilder()
.UseKestrel(options =>
{
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls(string.Format("http://localhost:{0}", _configuration.PortNumber))
.UseSetting("https_port",_configuration.HttpsPort.ToString())
.Build();
_restApiServer.Run();
REST API is served on port 8998 by default. This REST API is started by my different application. I am able to connect to this REST API using browser and POSTMAN.
Now I would like to secure my connection to REST API. What I did is: I've added necessity configuration to force secure connection in my Startup class in Configure method:
app.UseHttpsRedirection();
And I've also executed a code for trusting dev certs:
dotnet dev-certs https --trust
The case is that when I try to access the web api via browser I get and error:
localhost refused to connect. Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
Also when I am using POSTMAN to call some REST API methods I got and error:
Could not get any response
What am I doing wrong? Do I need to specify the certificate directly in Kestrel configuration?
Upvotes: 7
Views: 29162
Reputation:
Since https is a different protocol, you need to configure another port for https. There are three things you need to do in order to automatically redirect to the https url:
Add a listener. In program.cs (the port numbers are an example):
.UseUrls("http://localhost:8998", "https://localhost:8999");
When you start the application you should see:
Configure the https redirection. In Startup.ConfigureServices:
services.AddHttpsRedirection(options => options.HttpsPort = 8999);
If you omit this step then the default port is used, probably 5001. For hosting on Azure you may need to set this to 443.
And in Startup.Configure:
app.UseHttpsRedirection();
A call to http://localhost:8998
will now be redirected to https://localhost:8999
.
If you followed above steps but did not create the certificate then the https port is not listed and will not be available! If the certificate was created then both ports should be listed.
I assume that in production the Api will run behind a proxy. In that case you can omit the above steps. Running behind a proxy means that you can redirect http to https there, which means that you don't need https redirect.
Upvotes: 10