Blazor GetAsync请求返回401状态码 [英] Blazor GetAsync request returns 401 status code

查看:169
本文介绍了Blazor GetAsync请求返回401状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,尝试使用.NET Core / EF Core 3和Visual Studio 2019创建应用程序。我已经设置了数据库模型和API,以获取所有地址(/ api / Address)并浏览至此在浏览器中返回数据库中的所有记录。但是我的Razor文件中的My GetAsync方法返回401,最后返回null。

I am new to blazor and trying to create an application using .NET Core /EF Core 3 and Visual studio 2019. I have setup a database model and an API for getting all addresses (/api/Address) and browsing to this in a browser returns all of the records in the database. But my My GetAsync method in the Razor file returns 401 which finally returns null.

这是我的Razor代码:

Here is my Razor code:

@functions 
{
   Address[] addresses;
   protected override async Task OnInitializedAsync()
   {
     addresses = await Http.GetJsonAsync<Address[]>("api/Address");
   }
}

这是我的API

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class AddressController : ControllerBase
{
    private readonly MyDataContext _context;
    // GET: api/Address
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Address>>> GetAddresses()
    {
        return await _context.addressesDbSet.ToListAsync();
    }
}

我所得到的错误都是

 HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).

目前尚无进一步澄清,我无法理解原因,任何建议或建议都将不胜感激。

which has no further clarification and I am unable to understand the cause, any advice or suggestion would really appreciate.

推荐答案

我已经解决了这个问题,下面是我的解决方案,以防其他人遇到相同的问题。

I've solved the problem and below is my solution in case someone else got same problem.

注入HttpClient之后,我在调用GetAsSync之前将以下参数传递给HttpClient

After injecting HttpClient I passed the following parameters to HttpClient before calling GetAsSync

 var handler = new HttpClientHandler() 
  { 
           UseDefaultCredentials = false, Credentials = 
           System.Net.CredentialCache.DefaultCredentials, AllowAutoRedirect = true 
   };
    Http = new HttpClient(handler);
    Http.BaseAddress = new Uri(/*YOUR BASE Uri*/);

    Addresses = await Http.GetJsonAsync<Address[]>("api/Address");

这篇关于Blazor GetAsync请求返回401状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆