c# - 使用 REST 的客户端证书问题
问题描述
我有一个测试控制台应用程序正在使用 REST 监听请求:
主要方法:
static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration("https://localhost:8030");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}
控制器:
public class RestController : ApiController
{
[RequireHttps]
public string Get(int id)
{
return "value";
}
}
以及重写的 RequireHttpsAttribute 类。取自这里
这是正在侦听请求的应用程序的代码。到目前为止它运行良好,但我对发送请求的应用程序有一些问题:
以下是调用托管 REST-Controller 的应用程序代码:
public class Program
{
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
SEND();
}
public static async void SEND()
{
HttpClient lClient = null;
try
{
WebRequestHandler lHandler = new WebRequestHandler();
X509Certificate lCertificate = GetCert2("localhost");
lHandler.ClientCertificates.Add(lCertificate);
lHandler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
lHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
lClient = new HttpClient(lHandler);
Uri lWebService = new Uri("https://localhost:8030/api/rest/get");
var requestMessage = new HttpRequestMessage(HttpMethod.Get, lWebService);
Task<HttpResponseMessage> lRequest = lClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
HttpResponseMessage lResponse = lRequest.Result;
HttpStatusCode lStatusCode = lResponse.StatusCode;
HttpContent lResponseContent = lResponse.Content;
string lResponseText = await lResponseContent.ReadAsStringAsync();
if (!lResponse.IsSuccessStatusCode)
{
Console.WriteLine("Your Request failed : " + lResponse.ReasonPhrase + ":" + lResponseText);
}
else
{
Console.WriteLine("Request successful : " + lResponseText);
}
}
catch (Exception pEx)
{
Console.WriteLine("Exception occured : " + pEx.Message + " ; " + pEx.InnerException);
}
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
Console.WriteLine("Validating certificate {0}", certificate.Issuer);
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
private static X509Certificate2 GetCert2(string hostname)
{
X509Store myX509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
myX509Store.Open(OpenFlags.ReadWrite);
X509Certificate2 myCertificate = myX509Store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.GetNameInfo(X509NameType.SimpleName, false) == hostname);
return myCertificate;
}
不幸的是HttpContent lResponseContent = lResponse.Content;
,代码停止并告诉我连接已关闭。没有进一步的异常细节。我怀疑请求的格式不正确。
获取证书的代码正常工作并返回我在端口 8030 上安装的证书...
我在这里想念什么?
谢谢您的帮助
解决方案
推荐阅读
- python - Python将列拆分为最小值和最大值
- javascript - 是否可以将 blob 转换为 pptx?
- docker - 在自定义 GitHub 操作中挂载运行 docker-in-docker 容器的文件夹
- .net - 即使工作正常,Visio VSTO 中的 .NET OpenFileDialog FileNotFoundException
- server - 有没有办法在发布之前以服务器模式查看 Tableau 仪表板/工作表?
- php - API POST 请求返回 HTML 而不是 JSON 并且没有进入我的 HTML 元素
- c# - IOCPT/IOCP - 它只存在于 Windows 中吗?
- raku - 在 termux/android 上安装 Rakudo
- cmake - CPPCheck:本地头文件中的错误未被捕获
- go - 在 Gitlab 上使用私有 go 模块作为导入:“未知修订版”