[英]REST C#: why is my auth. request failing but postman works
I am doing a simple call to an api giving it a token:我正在对一个 api 进行简单的调用,给它一个令牌:
var url = baseUrl + "buildings";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await client.GetAsync(url);
string content = (response.Content.ReadAsStringAsync().Result);
From the debugger I know that the header looks like this:从调试器我知道标头看起来像这样:
I know for a fact that the token is correct.我知道令牌是正确的。
Here is the same in Postman which works:这在 Postman 中也是一样的:
Why is postman working and c# isnt?为什么邮递员在工作而 C# 不工作? The header should be the same.标题应该相同。 The returned message from the server is: JWT TOKEN NOT FOUND服务器返回的消息是:JWT TOKEN NOT FOUND
EDIT.编辑。
its gets more wired: I am able to access another api endpoint (different url, same base url) with the exact code as posted and the same token.它变得更加连贯:我能够使用发布的确切代码和相同的令牌访问另一个 api 端点(不同的 url,相同的基本 url)。 This works fine, but the base url returns TOKEN NOT FOUND, again, only not working in c#, while working from postman..?!?这工作正常,但基本 url 返回 TOKEN NOT FOUND,再次,只是不能在 c# 中工作,而在邮递员工作时......?!?
Because it's not an authorization or authentication header, it's just a header with the key "Authorization".因为它不是授权或身份验证标头,所以它只是带有“授权”键的标头。
Change this line:更改此行:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
to this:对此:
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
You can actually see that in Postman as well, in Postman there is a tab authorization which is (most likely) empty since there are no auth-headers present in the request.您实际上也可以在 Postman 中看到,在 Postman 中有一个选项卡授权(很可能)是空的,因为请求中不存在 auth-headers。
My code is correct.我的代码是正确的。 It turns out that the URL had to end on a "/" (slash).事实证明,URL 必须以“/”(斜杠)结尾。 Allthough postman did the auto generated code WITHOUT the "/", it is neccissarry in c#.尽管邮递员在没有“/”的情况下执行了自动生成的代码,但它在 c# 中是必需的。 Dont ask,...别问,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.