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

问题描述 投票:1回答:1

Web Api

[HttpGet]
[RequireHttps]
[Route("Api/GetString")]
public string GetString()
{
   return "Worked";
}

RequireHttpsAttribute类

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

是否需要配置?

谢谢。

c# asp.net-web-api client-certificates
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.