Blazor GetAsync request returns 401 status code

ⅰ亾dé卋堺 提交于 2020-01-25 10:21:09

问题


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.

Here is my Razor code:

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

And here is my 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();
    }
}

The error all I am getting says

 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.


回答1:


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

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");


来源:https://stackoverflow.com/questions/59327818/blazor-getasync-request-returns-401-status-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!