Home > Back-end >  Change HTTP PUT Request to HTTP PATCH Request using IAsyncActionFilter and rewrite the whole ActionD
Change HTTP PUT Request to HTTP PATCH Request using IAsyncActionFilter and rewrite the whole ActionD

Time:04-01

I am currently converting from Asp.Net Framework to Core and working on finding a way to change an HTTP PUT/POST request to PATCH when the Content-Type = "application/json-patch json". Changing the Method itself is NOT working. I think rewriting the whole ActionDescriptor will do the trick but I have no idea how to do it Below is the code I currently have.

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

CodePudding user response:

There's already 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 as a basis for your own middleware.

Alternatively, you could write it as an anonymous method in your startup's Configure method:

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

Whichever route you take, the middleware should be registered before your call to app.UseRouting();

  • Related