简体   繁体   中英

Http post works in Postman but not in C# with HttpClient

If I made a Http (Https) post through Postman everything works fine. But if I tried the same post with the HttpClient in .NET core it won't work it seems like the Authorization failed or something like that because the response.StatusCode is OK but if I read the content string I get a HTML page with 404 and its asking me if I like to login.

Of course I already checked the obvious things like the address and I tried different tokens (they always worked in postman). I also tried different versions of adding the Bearer token:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

This is the code at the moment:

client.BaseAddress = new Uri("www.baseaddress.de");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var content = new StringContent(JsonConvert.SerializeObject(new { id = object.Id }), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"/address", content);

Postman Headers: 邮递员标头

The body:

邮递员身体

I also tried it with insomnia and it works perfectly there too. Maybe postman do something in its header which I don't know? What are the common differences between postman an HttpClient? Does anyone have any other suggestion about what I could do or try to find the mistake?

Edit:

Fixed it by adding the / behind the base address and deleting it in front of the call:

client.BaseAddress = new Uri("www.baseaddress.de/");
HttpResponseMessage response = await client.PostAsync($"address", content);

Maybe anyone knows why the / is needed at the end of the base address, why can't I put it before the API call?

Instead of new { id = object.Id }.ToString() you need to do

JsonConvert.SerializeObject(new { id = object.Id })

Code like new { id = 77 }.ToString() produces "{ id = 77 }" , not "{ id: "77" }"

在类似的情况下,我将地址从http://...更改为https://...并解决了问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM