Blazor GetAsync 请求返回 401 状态代码 [英] Blazor GetAsync request returns 401 status code
问题描述
我是 blazor 的新手,正在尝试使用 .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屋!