这个端点如何响应404状态代码?

问题描述 投票:0回答:1

我在我的一个控制器的 ASP.NET核心 应用程序。

[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);
}

然而,有时我在调用这个端点时,得到的是404响应。当我查看日志时,我看到了这个。

  • 15:54:37.334: 请求开始HTTP1.1 POST https:/myurl我的方法 applicationx-www-form-urlencoded 0
  • 15:54:37.351: 成功验证令牌。
  • 15:54:37.351: 请求在18.0889ms内完成。404

所以端点被找到了,承载令牌被验证了... ...但还是出现了404响应。但这怎么可能呢? 我想说,我的方法的唯一可能的输出代码是200和500,对吗?

asp.net-core http-status-code-404 http-status-codes
1个回答
1
投票

我做了一个测试,如果不匹配任何操作,可以重现同样的问题。在我看来,日志 "Request starting HTTP/1.1 POST https://myurl/my-method..." 只是表明请求传入并由服务器开始处理,并不意味着找到了端点,并且击中了你的控制器动作方法。

控制器和动作

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

        return Ok(true);
    }

}

发出POST请求

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

日志

enter image description here

提出请求 api/values/my-method,效果良好

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

所以,请确认您是否申请 [Route(...)] 到您的控制器,并请确保您使用正确的URL路径进行请求。

© www.soinside.com 2019 - 2024. All rights reserved.