![](/img/trans.png)
[英]Status code 500, ReasonPhrase:'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent
[英]Getting StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers error when Calling a API via code
我嘗試調用外部 api,當我使用 Postman 時,它正在工作並返回如下值:
發布到 URL: https : //test.com/api/v1/users/check
要發布的數據原始傑森:
{
"access_token":"4444-EA444B6-2844C7-A09C-44B05CA78E42A3",
"email":"test@test.com",
"create_user": true,
"first_name": "test4",
"last_name": "test",
"phone": 3104054512
}
所以這是有效的並返回我的響應模型。
但是當嘗試使用此代碼調用 api 時:
控制器:
[Route("CreateUser")]
public Task<UserReturn> CreateUser([FromBody] User user)
{
return homebirdRepository.CreateUser(user);
}
public async Task<UserReturn> CreateUser(User userCheck)
{
using (GetWSObject<UserReturn> addObjectInt = new GetWSObject<UserReturn>())
{
return await addObjectInt.PostWSObjectModel("api/v1/users/check", userCheck, "API_URI");
}
}
public async Task<T> PostWSObjectModel(string uriActionString, Object model, string apiKey)
{
T returnValue = default(T);
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(WebConfigurationManager.AppSettings[apiKey]);
var content = new StringContent(JsonConvert.SerializeObject(model));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await client.PostAsync(uriActionString, content);
response.EnsureSuccessStatusCode();
var test = response.Content.ReadAsStringAsync().Result;
returnValue = JsonConvert.DeserializeObject<T>(((HttpResponseMessage)response).Content.ReadAsStringAsync().Result);
}
return returnValue;
}
catch (Exception e)
{
throw (e);
}
}
此代碼返回此錯誤:
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content:
System.Net.Http.StreamContent,
Headers:
{
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-
With
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Cache-Control: no-cache, private
Date: Sat, 28 Dec 2019 00:00:04 GMT
Set-Cookie:laravel_session=eyJpdiI6IlI2MUdzOFJmS0RcL1k1VmJCeTc4bk1nPT0iLCJ2YWx1ZSI6IlZXNW11MGw2bXk0ajFEaTM2VnhmbUZjQnFzdnRDRHV5ejJMaDRqTVJYQm1yclNyUUkweDNRMUhpZDZwblpES1MiLCJtYWMiOiI0NmFiODA4YzEyNTkxZDllNDViNGUwOGIzYjY2ZWYxZGQwNzI1NmZmYzYxYTBkZGU0M2NmMDBlYzIzN2E3OTFjIn0%3D; expires=Sat, 28-Dec-2019 02:00:04 GMT; Max-Age=7200; path=/; httponly
Server: Apache
Content-Length: 21
Content-Type: text/html; charset=UTF-8
}}
您很可能有一個在 Postman 中設置的 C# 中未設置的標頭、cookie 等。 有多種方法可以確定在 Postman 中設置了哪些屬性。 我在這里回答了一個類似的問題。 Fiddler 或其他一些單獨的工具不應該是必要的。
必須添加Authorization header,這個是postman添加計算的,可以copy/post。 如果您使用的是基本身份驗證,請執行以下操作。
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "從郵遞員復制的值");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.