1

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.

2
  • Does the Configure section in your startup.cs file have: endpoints.MapBlazorHub(); ? Commented Dec 13, 2019 at 18:43
  • Yes, it does already Commented Dec 13, 2019 at 19:08

2 Answers 2

7

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");
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for coming back to update us with the solution.
How did you solve the problem? How did you make GetJsonAsync work for you ? It didn't work for you before... Did you install the package: Microsoft.AspNetCore.Blazor.HttpClient ? Of course you did. But did you read: "Intended for use with Blazor running under WebAssembly" . But alas, your app is a Blazor Server one. Do you know that the HttpClient you are using now, on the server, is not the actual HttpClient, and it, for instance does not support WebSockets, etc. It is merely HTTP calls implemented in JavaScript.
OK, this is enough.... I just wanted others to be wary of your 'solution' . Incidentally, HttpClientHandler is not necessary here, and it is probably ignored.
I am going to agree that this should not be needed - - but I won't down vote it because I hate when people do that :) -- also, this code was used in a open source project that I worked on but only because we needed to support server side and client side Blazor in the same application, and we needed to manually pass authentication cookies. For a normal server side Blazor application this is not needed.
honestly, i wasn't too sure what was the cause for the error above (401), all i thought was authentication/ credentials related issue and when i passed the above handler parameters, it all went fine, but still trying to learn more...let me know what worked for you guys. thanks
0

I used named HTTPClient and got the same error (401) after I applied the following settings to the file launchSettings.json in Visual Studio:

"windowsAuthentication": true,
"anonymousAuthentication": false,

My solution is built upon that of @Medhanie W.:

     string baseUri = Configuration.GetValue<string>("BaseUri");
     services.AddHttpClient("LocalApi", client => 
     {
        client.BaseAddress = new Uri(baseUri);
     }).
     ConfigurePrimaryHttpMessageHandler(() => 
        new HttpClientHandler()
        {
           UseDefaultCredentials = false,
           Credentials = System.Net.CredentialCache.DefaultCredentials,
           AllowAutoRedirect = true
        };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.