首页 > 解决方案 > 为什么我的 Asp.Net Core 日志中出现“不支持 POST 请求”?

问题描述

我有一个 ASP.NET Core 5 API 设置。我还有一些使用静态内容的 Razor 页面。我正在使用 JWT 进行身份验证。在我的UserController我有一个操作存根,我正在开发一个更改密码操作:

    [Authorize]
    [HttpPost("ChangePassword")]
    public IActionResult ChangePassword([FromBody] string password)
    {
        HttpContext.Items.TryGetValue("User", out var user);

        _logger.ForContext<UsersController>().Debug("User {EmailAddress} tried to change his password to {Password}.", ((User)user).EmailAddress, password);

        return Ok();
    }

这可以使用 Swagger 进行测试并记录下来。我还有其他 POST 操作。这是我第一次尝试让用户使用HttpContext.

但是,仅使用此新操作,我的日志中才会出现两个条目:

2021 年 7 月 23 日 21:36:24.612 不支持 POST 请求
2021 年 7 月 23 日 21:36:24.605 不支持 POST 请求

日志 (Seq) 显示SourceContextis Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware

我想知道为什么我会收到这两个日志条目,我可以安全地忽略它们吗?

标签: c#asp.net-corejwt

解决方案


该日志条目来自StaticFileMiddleware检查它是否应该接管请求并返回文件响应。

public class StaticFileMiddleware
{
    // ...
    public Task Invoke(HttpContext context)
    {
        if (!ValidateNoEndpoint(context))
        {
            _logger.EndpointMatched();
        }
        else if (!ValidateMethod(context))
        {
            //  "POST requests are not supported"
            _logger.RequestMethodNotSupported(context.Request.Method);
        }
        else if (!ValidatePath(context, _matchUrl, out var subPath))
        {
            _logger.PathMismatch(subPath);
        }
        else if (!LookupContentType(_contentTypeProvider, _options, subPath, out var contentType))
        {
            _logger.FileTypeNotSupported(subPath);
        }
        else
        {
            // If we get here, we can try to serve the file
            return TryServeStaticFile(context, contentType, subPath);
        }

        return _next(context);
    }
}

由于它不提供静态文件,因此它调用链中的下一个中间件,最终让请求被分派到您的控制器。

您可以放心地忽略它。它是在Debug级别记录的,只有在您遇到静态文件问题时才重要。


推荐阅读