此请求的 C# 授权已被拒绝

C# Authorization has been denied for this request

我正在尝试使用令牌持有者身份验证从我的 .net Consoleapp 连接到远程 WebApi

尽管我的程序 returns 成功获得了一个令牌,但在我的 PostAsync 方法中我收到以下消息:

"Authorization has been denied for this request"

我的代码如下

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);

到目前为止一切顺利代码returns一个Token并将其存储在结果中

以下部分执行以下操作:使用我收到的令牌,我正在尝试检索一些数据

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 消息 "Authorization has been denied for this request" 我的代码中是否遗漏了一些重要的东西?任何帮助将不胜感激

您的请求可能如下所示:

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;

在您的代码中,您正在尝试 post 授权简介作为字符串内容,它应该在请求中 header。