我有一个自托管的WEB API项目,只需要通过HTTPS运行。
我发现了几篇文章如何做到这一点(获取SSL证书,使用'netsh'命令将证书绑定到IP /端口,将基地址更改为HTTPS:// ...等)。
到目前为止所有看起来都很好,我可以通过HTTPS调用该服务。
但我还需要明确拒绝所有HTTP调用。当我尝试使用HTTP调用服务时,我收到'504超时'错误。从服务获得响应需要一段时间,可能会获得拒绝服务。
我尝试应用自定义属性,该属性将检查请求是否来自HTTPS但是从未达到该代码。
我需要做什么才能拒绝HTTP调用。同样,它是一个自主的WEB API项目。
我没有在IIS中托管WEB API。它是一个自托管的WEB API。这是我初始化它的代码:
public class HttpsSelfHostConfiguration : HttpSelfHostConfiguration
{
public HttpsSelfHostConfiguration(string baseAddress) : base(baseAddress) { }
public HttpsSelfHostConfiguration(Uri baseAddress) : base(baseAddress) { }
protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
{
if (BaseAddress.ToString().ToLower().Contains("https://"))
{
httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
}
return base.OnConfigureBinding(httpBinding);
}
}
var url = "https://localhost:7080/";
var config = new HttpsSelfHostConfiguration(url);
config.Routes.MapHttpRoute("WebAPIRoute2", "api/{controller}/{action}/{id}",
new { controller = "Submissions", id = RouteParameter.Optional });
var server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
我还使用以下命令将SSL证书绑定到端口7080:
netsh http add urlacl url=https://+:7080/ user=Everyone
netsh http add sslcert ipport=0.0.0.0:7080 certhash=Thumbprint appid={xxxx}
答案 0 :(得分:0)
我猜你需要这样的东西
Best way in asp.net to force https for an entire site?
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
redirectType="Permanent" />
</rule>
</rules>
<outboundRules>
<rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
<match serverVariable="RESPONSE_Strict_Transport_Security"
pattern=".*" />
<conditions>
<add input="{HTTPS}" pattern="on" ignoreCase="true" />
</conditions>
<action type="Rewrite" value="max-age=31536000" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
{
Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+ HttpContext.Current.Request.RawUrl);
}
}