HttpClient的授权

3

我正在尝试使用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

我在Postman中使用基本身份验证没有遇到任何问题 @mjwills - Falcon
2
我使用以下代码进行基本身份验证:client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{LoginName}:{Password}"))); - Gusman
@Gusman之前尝试过。 返回相同的授权错误。 另外,你能解释一下区别吗? ;) - Falcon
1
你正在错误地使用 HttpClient,这会使你的软件不稳定。https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ - Wiktor Zychla
1
你正在添加“UserName”作为模式和“Password”作为内容,这将生成一个类似于Authorization: (username) (password)的头部,这对于基本授权是不正确的,基本授权应该像这样:Authorization: (schema) (data) 最终应该类似于这样:Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l - Gusman
1个回答

0

我可能错了,但你首先要声明一些头文件。

 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Utilities.Utility.Username(), Utilities.Utility.Password());

但是在几行之后,您会清除它们:

client.DefaultRequestHeaders.Clear();

我不是HttpClient的专家,但这没有意义。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接