Search code examples
c#blazorblazor-webassemblydotnet-httpclient

Blazor WASM - Controller not found when making a PostAsJsonAsync Request


I am building a WASM app for the first time, and have been following tutorials.

The Solution I have is composed of 3 projects created by the wizard (Client, Server and Shared).

I am having trouble when making the following request from the index page:

var msg = await Http.PostAsJsonAsync<u001_000_001>("api/u001_000_001", userRec);

If (msg.IsSuccessStatusCode) ClearUserScr();

In the Server project, I have a Controllers folder with a controller named u001-000-001Controller (although the class name in the file is u001_000_001Controller). The relevant lines of code from the controller class are as follows:

[ApiController]
[Route("api/[controller]")]
public class u001_000_001Controller : ControllerBase
{
    [HttpPost]
    public async Task<u001_000_001> Post([FromBody] u001_000_001 create)
    {
        EntityEntry<u001_000_001> user = await db.u001_000_001.AddAsync(create);
        await db.SaveChangesAsync();
        return user.Entity;
    }
}

The HttpClient is registered using the builder.HostEnvironment.baseAddress as the Uri in the Client Program.cs file.

The Shared folder contains the handler called u001-000-001 (class name u001_000_001).

I have tried all the different combinations I can think of in terms of changing the names in the actual call, and nothing works. I keep getting the same "not found - HTTP 400' error.

I would sincerely appreciate help from experienced eyes to see if there is a simple mistake I'm making or if there's something more serious I'm missing. Many thanks in advance for your time.


Solution

  • Many hours of research later, the error was found to be in the fields being fed initially into the handler, rather than anything happening with the actual HttpClient request or the controller.

    Although I found that the Http/1.1 400 Bad request error could be generated by a range of issues, I would highly recommend reviewing the structure of the data being input as a first step, since this was overlooked in my case.

    Clarification of Issue and Solution: I have a process for creating new user logins, and the goal of the HttpClient PostAsJsonAsync request was to send new account details to the database. However one of the fields in the user record is a PIN number, and as this is not chosen by the new user in the first registration step, it was left as null in the code.

    Keeping it null was fine for the code, but the Controller expects data to be input for all fields, and will not accept PostAsJsonAsync calls where any of the fields are left null.

    The solution in my case was to set a temporary value, and then make the PostAsJsonAsync request with all of the fields filled and sent through the request.

    I wish to thank the professionals who commented with potential solutions, as they helped to improve my code.