使用 IAsyncActionFilter 将 HTTP PUT 请求更改为 HTTP PATCH 请求,并在 Asp.net Core 中重写整个 ActionDescriptor

Change HTTP PUT Request to HTTP PATCH Request using IAsyncActionFilter and rewrite the whole ActionDescriptor in Asp.net Core

我目前正在从 Asp.Net Framework 转换到 Core 并致力于寻找一种方法,当 Content-Type = "application/json-patch+[ 时将 HTTP PUT/POST 请求更改为 PATCH =17=]”。更改方法本身不起作用。我认为重写整个 ActionDescriptor 可以解决问题,但我不知道该怎么做下面是我目前拥有的代码。

public class FewzionActionSelector : IAsyncActionFilter {
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
        // Execute the rest of the MVC filter pipeline
        if (context.HttpContext.Request.ContentType != null && context.HttpContext.Request.ContentType.Equals("application/json-patch+json"))
        {
            if (context.HttpContext.Request.Method.Equals(HttpMethod.Put.Method) || context.HttpContext.Request.Method.Equals(HttpMethod.Post.Method))
            {
                context.HttpContext.Request.Method = $"{HttpMethod.Patch.Method}";
                if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
                {
                    var actionAttributes = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true);

                }
            }
        }
        await next();
    }
}

已经有 UseHttpMethodOverride baked into ASP.NET Core, and though it doesn't quite work exactly how you want it to, you could use the corresponding middleware's code 作为您自己的中间件的基础。

或者,您可以将其编写为您启动的 Configure 方法中的匿名方法:

app.Use(async (context, next) =>
{
    if (string.Equals(context.Request.ContentType, "application/json-patch+json") 
        && (context.Request.Method.Equals(HttpMethod.Post) || context.Request.Method.Equals(HttpMethod.Put)))
    {
        context.Request.Method = HttpMethod.Patch.Method;
    }
    await next();
});

无论采用哪种方式,中间件都应该在调用 app.UseRouting();

之前注册