Search code examples
asp.net-corehttp-status-code-404http-status-codes

How can this endpoint respond a 404 status code?


I have this method in one controller of my ASP.NET Core application:

[HttpPost("my-method")]
[Authorize(Policies.ADMIN, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public async Task<ActionResult<bool>> MyMethod()
{
    try
    {
        await DoWork();
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error while doing work");
        return StatusCode(500, false);
    }

    return Ok(true);
}

However, sometimes I get a 404 response when calling this endpoint. When I look at the logs, I see this:

  • 15:54:37.334: Request starting HTTP/1.1 POST https://myurl/my-method application/x-www-form-urlencoded 0
  • 15:54:37.351: Successfully validated the token.
  • 15:54:37.351: Request finished in 18.0889ms 404

So the endpoint is found, the bearer token is validated... and yet there it is the 404 response. But how can it be? I'd say that the only possible output codes from my method are 200 and 500, right?


Solution

  • I did a test and can reproduce same issue if it does not match any action. And in my view, the log "Request starting HTTP/1.1 POST https://myurl/my-method..." just indicates that the request is incoming and server starts processing it, not mean that the endpoint is found and it hits your controller action method.

    Controller and Action

    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class ValuesController : ControllerBase
    {
        [HttpPost("my-method")]
        public async Task<ActionResult<bool>> MyMethod()
        {        
            //...
    
            return Ok(true);
        }
    
    }
    

    Make a POST request

    POST https://localhost:5001/my-method
    

    Logs

    enter image description here

    Make request to api/values/my-method, which works well

    POST https://localhost:5001/api/values/my-method
    

    So please check if you apply [Route(...)] to your controller and please make sure you make request with correct URL path.