[英]C# Authorization has been denied for this request
I am trying to connect with a token bearer Authentication into a remote WebApi
from my .net Consoleapp
. 我试图用一个令牌承载身份验证连接到远程WebApi
从我的.net Consoleapp
。
Despite the fact that my program returns with a success a token, in my PostAsync
Method i get the following message: 尽管我的程序成功返回了令牌,但在我的PostAsync
方法中,我PostAsync
收到以下消息:
"Authorization has been denied for this request" “此请求的授权已被拒绝”
My code is the following 我的代码如下
hHttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
HttpContent Content = new StringContent(string.Format("grant_type=password&username={0}&password={1}",
HttpUtility.UrlEncode(ApiLoginUsername),
HttpUtility.UrlEncode(ApiLoginPassword)), Encoding.UTF8,
"application/x-www-form-urlencoded");
HttpResponseMessage response = client.PostAsync("/api/login", Content).Result;
string resultJSON = response.Content.ReadAsStringAsync().Result;
result = JsonConvert.DeserializeObject<LoginTokenResult>(resultJSON);
So far so good the code returns a Token and stores it in the result 到目前为止,代码返回了一个令牌并将其存储在结果中
The following part does the following with: With the token that i received i am trying to retrive some data 以下部分将执行以下操作:使用收到的令牌,我试图检索一些数据
HttpContent TestContent = new StringContent(string.Format("Authorization","Bearer"+ result.AccessToken,"application/json"));
var Product = client.PostAsync("/api/Report",TestContent).Result;----> This is where it says Authorization denied
var test = Product.Content.ReadAsStringAsync().Result;
return result;
Why am i getting in the test
the message "Authorization has been denied for this request" Am i missing something important in my code? 为什么在test
出现“此请求已拒绝授权”消息,我的代码中缺少重要的内容吗? Any help would be appreciated 任何帮助,将不胜感激
Your request could look something like this: 您的请求可能如下所示:
string uri = "/api/Report";
string token = "<token here>";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("<base address>");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Headers.Add("Authorization", string.Format("bearer {0}", token);
HttpResponseMessage response = client.SendAsync(request).Result;
In your code you are trying to post the Authorization blurb as string content where it should be in the request header. 在您的代码中,您尝试将Authorization blurb作为字符串内容发布到应在请求标头中的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.