【发布时间】:2017-03-30 04:31:20
【问题描述】:
网页接口
[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,它可以正常工作。
有什么需要配置的吗?
谢谢。
【问题讨论】:
-
尝试删除您的自定义属性,看看它是否在没有它的情况下通过 https 工作。
-
如果我删除 [RequireHttps] 并通过 Http 访问相同的方法,它可以工作。
-
尝试通过 https 删除和访问。它可能表明问题出在您的属性上。
-
@AndriiLitvinov 感谢您的建议,但它的行为相同。
-
在浏览器或您的客户端中工作方式相同?尝试创建新的 web api 项目并确保它在浏览器中与 https 一起使用。然后逐步添加新功能以缩小问题范围。
标签: c# asp.net-web-api client-certificates