2017-04-26 10 views
0

Ich bin neu in der C# HttpClient-Klasse und ich hoffe euch & Mädels können mir mit meinem Problem helfen. Ich erhalte den Statuscode 401, wenn ich versuche, die PostAsync-Methode aufzurufen. Hier ist mein CodeStatusCode 401 Grund Nicht autorisiert beim Aufruf von PostAsync WebRequest

public WebClient(HttpClient httpClient) 
    { 
     string webHost = ConfigurationManager.AppSettings["webHost"]; 
     string webApiKey = ConfigurationManager.AppSettings["webApikey"]; 

     _httpClient = httpClient; 
     _httpClient.BaseAddress = new Uri(webHost); 
     _httpClient.DefaultRequestHeaders.Accept.Clear(); 
     _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); 

     _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("x-coupa-api-key", "=" + ConfigurationManager.AppSettings["coupaApikey"]); 
     System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; 
    } 

public Tuple<bool, Task<HttpResponseMessage>> Comment(comment comment) 
    { 
     try 
     { 
      string commentUrl = string.Format("{0}api/comments/", _webHost); 
      var responseMessage = _httpClient.PostAsync(commentUrl, CreateHttpContent(comment)); 
      Log.Error("Response message: " + responseMessage.Result); 
      return new Tuple<bool, Task<HttpResponseMessage>>(responseMessage.Result.IsSuccessStatusCode, responseMessage); 

     } 
     catch (Exception ex) 
     { 
      Log.Error("Call to Web failed.", ex); 
      throw; 
     } 

    } 

private static HttpContent CreateHttpContent(comment data) 
    { 
     var format = "application/xml"; 

     return new StringContent(Common.SerializeUtf8(data), Encoding.UTF8, format); 
    } 

Also habe ich eine XML mit einem POST an einen Webhost sende - und ich erhalte das folgende Ergebnis aus PostAsync:

Response-Nachricht:

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 
{ 
    Transfer-Encoding: chunked 
    Status: 401 Unauthorized 
    X-Frame-Options: SAMEORIGIN 
    X-XSS-Protection: 1; mode=block 
    X-Content-Type-Options: nosniff 
    X-Request-Id: 53e17930-f9fe-4ec4-ae5b-b772ce5f308e 
    X-Runtime: 0.025822 
    Cache-Control: no-cache 
    Date: Wed, 26 Apr 2017 06:07:39 GMT 
    Content-Type: text/html 
} 

Antwort

1

die Lösung gefunden. Sollte die Autorisierung nicht verwendet haben, einfach "Header hinzufügen":

_httpClient.DefaultRequestHeaders.Add("x-coupa-api-key", ConfigurationManager.AppSettings["webApikey"]); 
Verwandte Themen