2014-07-07 143 views
9

我試圖做一個簡單的請求到Basecamp API,我遵循提供的說明添加樣本用戶代理和我的憑據,但我不斷收到403 Forbidden迴應。HttpClient和設置授權標頭

我的憑證絕對正確,所以我的請求/憑證設置不正確?

這是我(刪除個人信息):

var httpClient = new HttpClient(); 
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") }); 

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", 
      Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")))); 

var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content); 
var responseContent = response.Content; 

using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync())) 
{ 
    Console.WriteLine(await reader.ReadToEndAsync()); 
} 

回答

15

就讓我們來看看在他們的文件似乎表明projects.json端點接受該職位的身體下面:

{ 
    "name": "This is my new project!", 
    "description": "It's going to run real smooth" 
} 

您發送User-Agent作爲POST正文。我建議你改變你的代碼如下:

var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))); 
    using (var httpClient = new HttpClient()) 
    { 
     httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]"); 
     httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials); 
     var response = await httpClient.PostAsJsonAsync(
      "https://basecamp.com/[USER ID]/api/v1/projects.json", 
      new { 
       name = "My Project", 
       description = "My Project Description" 
      }); 

     var responseContent = await response.Content.ReadAsStringAsync(); 
     Console.WriteLine(responseContent); 
    } 

這個職位作爲文件規定,並設置您的用戶代理的頭,因爲它應該是有效載荷。

+0

謝謝,不得不修改這一點,但得到它 – DGibbs

+0

當時沒有編碼IDE,或許應該說是:) –

+0

也請考慮爲什麼包裝客戶端成短命'using' _might_壞工作:HTTP: //stackoverflow.com/questions/22560971/what-is-the-overhead-of-creating-a-new-httpclient-per-call-in-a-webapi-client – mmlac