且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为Asp.net核心Web API启用HTTPS安全连接

更新时间:2022-11-06 19:13:33

由于https是不同的协议,因此您需要为https配置另一个端口.要自动重定向到https网址,您需要做三件事:

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:

  1. 添加一个侦听器.在program.cs中(端口号为示例):

  1. 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:

  1. 配置https重定向.在Startup.ConfigureServices中:

  1. Configure the https redirection. In Startup.ConfigureServices:

services.AddHttpsRedirection(options => options.HttpsPort = 8999);

如果省略此步骤,则使用默认端口,可能是5001.要在Azure上托管,可能需要将此端口设置为443.

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.

并在Startup.Configure中:

And in Startup.Configure:

app.UseHttpsRedirection();

http://localhost:8998的调用现在将被重定向到https://localhost:8999.

A call to http://localhost:8998 will now be redirected to https://localhost:8999.

如果您按照上述步骤操作但未创建证书,则https端口未列出并且将不可用!如果创建了证书,则应列出两个端口.

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.

我认为在生产中,Api将在代理后面运行.在这种情况下,您可以省略上述步骤.在代理后面运行意味着您可以将http重定向到那里的https,这意味着您不需要

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.