2017-09-26 186 views
0

我試圖使用永久令牌的授權來發布JSON與HhttpClient使用HttpClient的,但我總是得到一個錯誤401未經授權的代碼:授權永久的令牌頭添加到POST JSON的REST API

public static async Task<Uri> CrearitemAsync(Item item) 
{ 
    using (var client = new HttpClient()) 
    { 
     client.BaseAddress = new Uri(BaseUri); 
     client.DefaultRequestHeaders.Accept.Clear(); 
     client.DefaultRequestHeaders.Authorization = 
      new AuthenticationHeaderValue("OAuth", AuthToken); 
     HttpResponseMessage response = await client.PostAsJsonAsync(
      "items/" + IdProvider, JsonConvert.SerializeObject(item)); 
     response.EnsureSuccessStatusCode(); 
     return response.Headers.Location; 
    } 
} 

我也試試這個:

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthToken); 

令牌似乎很好。它是一個全部小寫的字母數字字符串。這是使用永久令牌的正確方法嗎?

更新的關鍵,我必須使用的標題是:IDENTITY_KEY 但仍然未能

+0

沒有直接關係,但是[你正在使用'HttpClient'錯誤](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/)。 –

+0

[設置HttpClient的授權標頭]可能的重複(https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient) – Cory

+0

不要手動序列化項目(JsonConvert.SerializeObject)。只需將* item *傳遞給PostAsJsonAsync。 (或使用* StringContent *和* JsonConvert.SerializeObject *)手動執行它 –

回答

1

終於將其與添加的工作..有在標題中使用這個「關鍵」價值,而不是授權:

client.DefaultRequestHeaders.Add("IDENTITY_KEY", AuthToken);