简体   繁体   English

ASP.NET核心句柄方法不允许405

[英]ASP.NET Core handle Method Not Allowed 405

Developing an API platform that needs to be consistent through App Service itself and covering Azure API Management Service - I found myself stuck with an inconsistencies between both. 开发一个需要通过App Service本身保持一致并覆盖Azure API管理服务的API平台 - 我发现自己陷入了两者之间的不一致。

Sending a request with improper HTTP verb (eg PUT instead of POST) to API Management service results with 404 Not found response ( due to a known issue ). 使用不正确的HTTP谓词(例如PUT而不是POST)向API Management服务结果发送404 Not found响应( 由于已知问题 )。

Sending same request directly to ASP Core 2.2 based app would result in 405 Not Allowed response. 直接向基于ASP Core 2.2的应用程序发送相同的请求将导致405 Not Allowed响应。

Is there any possibility in ASP Core (possibly middleware) to catch 405 response code result and change it to 404? ASP Core(可能是中间件)是否有可能捕获405响应代码结果并将其更改为404?

Not sure if I'm a fan of just doing blind status code conversion. 不确定我是否只是盲目状态代码转换的粉丝。 Up to you based on your exact scenario, of course. 当然,根据您的具体情况由您决定。

This bit of middleware injected in your Configure method would do the trick: 在您的Configure方法中注入的这些中间件可以解决这个问题:

public void Configure(IApplicationBuilder app)
{
    app.Use(next => context =>
    {
        context.Response.OnStarting(() =>
        {
            if (context.Response.StatusCode == 405)
            {
                context.Response.StatusCode = 404;
            }

            return Task.CompletedTask;
        });

        return next(context);
    });
}

NOTE: Add this early in the chain. 注意:在链中尽早添加。

This is something that you can handle with the StatusCodePages middleware. 这是您可以使用StatusCodePages中间件处理的内容。 Here's an example: 这是一个例子:

app.UseStatusCodePages(ctx =>
{
    if (ctx.HttpContext.Response.StatusCode == 405)
        ctx.HttpContext.Response.StatusCode = 404;

    return Task.CompletedTask;
});

The argument passed into UseStatusCodePages is a callback function that is executed whenever the middleware detects a response with a status code between 400 and 599 (with an empty body). 传递给UseStatusCodePages的参数是一个回调函数,只要中间件检测到状态代码介于400和599之间的响应(空体),就会执行该回调函数。 In the example above, we simply check for 405 and change it to 404 . 在上面的示例中,我们只检查405并将其更改为404 The call to UseStatusCodePages itself must be placed before any request-handling middleware, such as MVC. UseStatusCodePages本身的调用必须放在任何请求处理中间件(如MVC)之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM