我正在尝试使用 ASP MVC 从 Wep API 获取一些数据。 我制作了一个新 Controller 并添加了所需的命名空间。 但出于某种原因,我不断收到错误 401 - 未经授权。我错过了什么?
public async Task<ActionResult> Index()
{
List<LanguageModel> LangInfo = new List<LanguageModel>();
var credentials = new NetworkCredential(Utilities.Utility.Username(), Utilities.Utility.Password());
var handler = new HttpClientHandler { Credentials = credentials };
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Utilities.Utility.Username(), Utilities.Utility.Password());
//Passing service base url
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("/api1/....removed sensitive link");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var LangResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
LangInfo = JsonConvert.DeserializeObject<List<LanguageModel>>(LangResponse);
}
//returning the employee list to view
return View(LangInfo);
}
}
出于某种原因,它没有提供处理程序?对此有点陌生,提前抱歉:)
从 Res 返回:
+ Res {StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Set-Cookie: syracuse.sid.8124=60f4b5c6-4a14-47bb-94fd-fff9ea670bdf; path=/;HttpOnly;
Set-Cookie: client.id=cdaf1589-38bf-47db-a3e6-0a9fb742190b; path=/; expires=Sun, 07 Oct 2018 21:12:58 GMT;HttpOnly;
WWW-Authenticate: Redirect /auth/login/page
x-frame-options: DENY
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
content-security-policy: frame-ancestors 'self';
cache-control: no-store, must-revalidate, proxy-revalidate, no-cache, max-age=0, s-maxage=0, private
pragma: no-cache
Date: Wed, 21 Mar 2018 21:12:58 GMT
Connection: keep-alive
Transfer-Encoding: chunked
Content-Type: application/json
content-language: en-US
}} System.Net.Http.HttpResponseMessage
最佳答案
我可能会弄错,但您首先要声明一些 header 。
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Utilities.Utility.Username(), Utilities.Utility.Password());
但几行之后你清除了它们:
client.DefaultRequestHeaders.Clear();
我不是 HttpClient 方面的专家,但这没有意义。
关于c# - HttpClient的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49416459/