Web Api
[HttpGet]
[RequireHttps]
[Route("Api/GetString")]
public string GetString()
{
return "Worked";
}
RequireHttpsAttribute class
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
var cert = actionContext.Request.GetClientCertificate();
if (cert == null)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "Client Certificate Required"
};
}
base.OnAuthorization(actionContext);
}
}
}
客户端(控制台)
HttpWebRequest client = (HttpWebRequest)WebRequest.Create("https://localhost:44315/api/GetString");
var cert = new X509Certificate2(File.ReadAllBytes(@"C:\ConsoleClient\TestCertificate.pfx"), "password");
client.ClientCertificates.Add(cert);
HttpWebResponse resp = (HttpWebResponse)client.GetResponse();
using (var readStream = new StreamReader(resp.GetResponseStream()))
{
Console.WriteLine(readStream.ReadToEnd());
}
此https请求引发错误。
Inner Exception Message : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Message : The underlying connection was closed: An unexpected error occurred on a send.
我打开了端口443并尝试了相同类型问题的答案中提到的一些设置,但无法解决。通过浏览器直接访问https://localhost:44315/api/GetString也无效。
如果我将https更改为http,它可以正常工作。
是否需要配置?
感谢。