使用REST的客户证书问题

时间:2018-09-24 13:52:41

标签: c# rest certificate

我有一个测试控制台应用程序,它正在使用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类。取自here

这是侦听请求的应用程序的代码。到目前为止,它运行良好,但是发送请求的应用程序存在一些问题:

这是调用托管的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上安装的证书...

我在这里想念什么?

谢谢您的帮助

0 个答案:

没有答案
相关问题