2015-12-17 35 views
1

我正在嘗試發佈到使用基本身份驗證的Web API。當我使用Fiddler進行POST時,我能夠成功發佈數據。現在我試圖在C#控制檯應用程序中做同樣的事情,但我仍然得到401未經授權的響應。在代碼中發佈到Web API返回「未授權」

當我通過調試運行代碼時,我可以播種憑證正在正確獲取Base64編碼。在網上做一些研究,我相信我有正確的代碼。任何人看到我是否錯過了什麼?

if (lstEmployee != null && lstEmployee.Count > 0) 
{ 
    try 
    { 
     using (var client = new HttpClient()) 
     { 
      client.BaseAddress = new Uri("https://website.com/api/employees/upload";); 


      //set credentials and add them to the client header 
      string credentials = Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));  
      client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials); 


      //set to use JSON 
      client.DefaultRequestHeaders.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 


      foreach (var employee in lstEmployee) 
      { 
       //Convert to JSON with Newtonsoft 
       string employeeJSON = JsonConvert.SerializeObject(employee); 


       HttpResponseMessage response = client.PostAsJsonAsync(fullServiceURL, employeeJSON).Result; 


       if (response.IsSuccessStatusCode) 
       { 
        //If successfull, do something. 

       } 
       else 
       { 
        logger.Error("Error posting to Web API. Employee: {0} | {1} ({2})", employee.EmployeeNumber, (int)response.StatusCode, response.ReasonPhrase); 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     logger.Error("Error posting to Web API. | {0} | Trace: {1}", ex.Message, ex.StackTrace); 
    } 
} 
else 
{ 
    logger.Info("No records found."); 
} 

在菲德勒我只是添加了以下到作曲家選項卡中的頭與身體中的一些JSON數據一起和它的工作。

Authorization: Basic abChaXJ3YXlzLmludGVncmF0aW9uOnRlc3Q0ZGNhYTIwMTU= 
Host: services.website.com 
Content-Length: 374 
Content-Type: application/json; charset=utf-8 

**更新**

我調整了代碼如下。現在,我收到錯誤狀態400「錯誤請求」。它似乎在抱怨數據格式不正確。但是,我記錄了JSON列表值並將其添加到Fiddler的主體中。我可以在Fiddler中發佈捕獲的JSON就好了。我不知道還有什麼要檢查的,看看它有什麼問題。

這是我的JSON列表經過Newtonsoft後的結果。我只拉用於測試目的

[{"EmployeeNumber":"22449","CompanyHireDate":"2014-12-15T00:00:00","Username":"EN022449","LastName":"AVIVA","FirstName":"JOE","MiddleInitial":null,"BirthDate":"1967-10-06T00:00:00","PhoneNumber":null,"EmailAddress":"[email protected]","Location":"BOS","Address1":null,"Address2":null,"City":null,"State":null,"Zip":null,"OverrideSeniorityOrder":0}] 

這是我更新的代碼的一個記錄:

if (lstEmployee != null && lstEmployee.Count > 0) 
{ 
    logger.Info("Employee count: " + lstEmployee.Count); 

    string baseUrl = "https://services.website.com/api/"; 
    string serviceUrl = "employees/upload"; 

    string fullServiceURL = baseUrl + serviceUrl; 
    logger.Debug("Web API Uri: " + fullServiceURL); 

    try 
    { 
     //Convert the list to JSON 
     string employeeJSON = JsonConvert.SerializeObject(lstEmployee); 
     logger.Debug("employeeJSON: " + employeeJSON); 

     //Add credentials to Client Handler 
     var credentials = new NetworkCredential("username", "password"); 
     var handler = new HttpClientHandler { Credentials = credentials }; 

     using (var client = new HttpClient(handler)) 
     { 
      //set URI and to use JSON 
      client.BaseAddress = new Uri(fullServiceURL); 
      client.DefaultRequestHeaders.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      HttpResponseMessage response = client.PostAsJsonAsync(fullServiceURL, employeeJSON).Result; 
      if (response.IsSuccessStatusCode) 
      { 
       //success 
      } 
      else 
      { 
       logger.Error("Error posting to Web API. {0} ({1})", (int)response.StatusCode, response.ReasonPhrase); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     logger.Error("Error posting to Web API. | {0} | Trace: {1}", ex.Message, ex.StackTrace); 
    } 
} 
else 
{ 
    logger.Info("No records found."); 
} 
+1

在設置授權標頭後,您可以這樣做:'client.DefaultRequestHeaders.Clear();'可以付費重新排序操作。 –

+0

謝謝。這讓我更加接近。我也應該看到這一點,但一遍又一遍地看後,我錯過了這一點。我收到了一個不同的錯誤,但至少它不是未經授權的。 – Caverman

+0

什麼是新錯誤?用相關細節更新你的問題。 –

回答

1

的HttpClientHandler,在.NET 4.5介紹,從有手工編碼認證頭爲您節省。像這樣使用它:

var credentials = new NetworkCredential(userName, password); 
var handler = new HttpClientHandler { Credentials = credentials }; 
using (var http = new HttpClient(handler)) 
{ 
    // ... 
} 
+0

感謝您的摘錄。是默認的基本身份驗證?或者,我需要具體使用Basic嗎? – Caverman

+0

我會假設它與服務器進行協商。但是如果您知道要使用基本身份驗證,則可以在HttpClientHandler上設置PreAuthenticate = true。這將立即添加驗證頭,並跳過挑戰/響應往返服務器。 –

相關問題