2017-10-05 99 views
1

我試圖使用.NET Core 2向第三方端點發出Web請求。端點需要使用客戶端證書和用戶名和密碼進行身份驗證。到目前爲止,我嘗試的所有內容都會導致403(禁止)錯誤。到目前爲止,我已經試過如下:使用.NET Core進行HTTP請求導致403 Forbidden錯誤

try 
{ 
    var handler = new HttpClientHandler(); 
    handler.Credentials = new NetworkCredential(username, password); 
    handler.ClientCertificateOptions = ClientCertificateOption.Manual; 
    handler.SslProtocols = SslProtocols.Tls12; 
    handler.ClientCertificates.Add(new X509Certificate2(certificate)); 

    var client = new HttpClient(handler); 
    var result = await client.GetStringAsync(url); 
} 
catch (Exception e) 
{ 
    Console.WriteLine(e); 
    throw; 
} 

我也試過:

try 
{ 
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 
    var request = (HttpWebRequest)WebRequest.Create(url); 
    var cert = new X509Certificate2(certificate); 
    request.ClientCertificates.Add(cert); 
    request.Credentials = new NetworkCredential(username, password); 
    request.Method = "GET"; 

    var response = (HttpWebResponse)request.GetResponse(); 
} 
catch (Exception e) 
{ 
    Console.WriteLine(e); 
    throw; 
} 

到目前爲止,我只是試圖做一個GET,但最終我需要做一個POST 。

正如我上面所說的,兩者都會導致403.如果我對.NET Framework運行第二個示例,它工作得很好。此外,如果我有提琴手運行,然後我得到一個OK狀態返回,而不是一個403.

任何想我做錯了,是阻止.NET核心成功連接到端點?

+0

也許你錯過了一些頭,比如Accept-Language,Content-Type。 – anserk

+0

我試過添加不同的頭文件,至今沒有任何工作。 –

回答

1

我最終將代碼切換到了我在下面的代碼中,並且做到了這一點。我將ClientCertificateOption設置爲「自動」,並手動刪除指定證書。

try 
{ 
    var handler = new HttpClientHandler(); 
    handler.Credentials = new NetworkCredential(username, password); 
    handler.ClientCertificateOptions = ClientCertificateOption.Automatic; 
    handler.SslProtocols = SslProtocols.Tls12; 

    var client = new HttpClient(handler); 
    var result = await client.GetStringAsync(url); 
} 
catch (Exception e) 
{ 
    Console.WriteLine(e); 
    throw; 
}