Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Posting to async controller method in ASP.NET Core results in HTTP 405 error

$
0
0

I'm trying to post to a controller method that asynchronously calls a data repository function to look up users. However I think there's some way that I've written the method poorly as when I try and call it I get returned a 405 HTTP error code. Other functions in this controller work as they are not async.

I call the controller method via a HttpClient service from a Razor page.

Calling the controller method:

var response = await Http.PostAsJsonAsync(nvgm.BaseUri +"api/User/check", user);

Controller code:

[ApiController][Route("api/[Controller]")]public class UserController : ControllerBase{    private readonly IUserRepo _repo;    public UserController(IUserRepo repo)    {        _repo = repo;    }    // ...    [HttpPost]    [Route("check")]    public async Task<String> checkUser([FromBody] User givenUser)    {        User? user = await _repo.GetByEmailAsync(givenUser.Email);        if (user != null)        {            return user.Name;        }        else        {            return "no work";        }    }} 

Repo function:

public async Task<User?> GetByEmailAsync(string email){    return await _context.Users.FirstOrDefaultAsync(u => u.Email == email);}

A workaround I could do is that I can call a normal method and then call the async method but then that ignores the advantages of using asynchronous methods.

To clarify too, this project is using .NET 9.

Any help is appreciated, thanks.

EDIT: To clarify, as Henk has stated, the code I've provided requires [FromBody] in the parameter of the controller method to specify that you need to find it in the body of the request. But due to poor writing on my end I realised that I have this in my own solution but not in this question, so I have since updated it.

Also want to mention that I have tested a different method in this controller that is routed to just fine. It even calls the async method without issue (but note it doesn't call it asynchronously). The test method code:

[HttpPost][Route("test")]public String checkCheck([FromBody] User user){     var asyncTest = checkUser(user);    return "valid";}

Viewing all articles
Browse latest Browse all 4839

Trending Articles