ASP.NET Web API:远程主机强制关闭现有连接

时间:2017-03-30 04:31:20

标签: c# asp.net-web-api client-certificates

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,它可以正常工作。

是否需要配置?

感谢。

1 个答案:

答案 0 :(得分:0)

对我来说,解决方案是通过https://stackoverflow.com/a/46223433/352432将https协议从默认的ssl3更新为tls