我正在尝试使用ASP MVC从Web API获取数据。 我创建了一个新的控制器并添加了所需的命名空间。 但是由于某种原因,我始终收到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
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{LoginName}:{Password}")));
- GusmanHttpClient
,这会使你的软件不稳定。https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ - Wiktor ZychlaAuthorization: (username) (password)
的头部,这对于基本授权是不正确的,基本授权应该像这样:Authorization: (schema) (data)
最终应该类似于这样:Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
。 - Gusman