我正尝试将令牌承载身份验证连接到WebApi
的远程.net Consoleapp
。
尽管我的程序成功返回一个令牌,但在我的PostAsync
方法中,我收到以下消息:
"此请求已拒绝授权"
我的代码如下
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);
到目前为止,代码返回一个令牌并将其存储在结果
中以下部分执行以下操作:使用我收到的令牌,我正在尝试检索某些数据
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;
为什么我会收到test
消息&#34;此请求已拒绝授权&#34;
我错过了我的代码中的重要内容吗?任何帮助将不胜感激
答案 0 :(得分:1)
您的请求可能如下所示:
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;
在您的代码中,您尝试将Authorization blurb作为字符串内容发布到请求标头中。