Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core http delete `FromBody` ignore if no content type header

I am using a body in a http DELETE request. I know having a body in a delete is non-standard at the moment (but is permissible).

The problem is occurring when using the HttpClient which does not allow a body for delete requests. I know I can just use SendAsync, but I would rather make my API more flexible.

I want this body to be optional. In the sense that if asp.net core cannot ascertain the content type then ignore it. At the moment, asp.net core is returning a 415, even though no body is being sent (via the HttpClient - so content length should be 0).

Can FromBody be extended in this way? Or would I need some custom logic in the pipeline?

like image 624
Umair Avatar asked Oct 17 '25 15:10

Umair


1 Answers

You can create ResourceFilter which is executed before Model Binding where content type is checked:

public class AddMissingContentType : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        context.HttpContext.Request.Headers["Content-Type"] = "application/json";
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}

And add it to your method:

[AddMissingContentType]
[HttpDelete]
public async Task<IActionResult> Delete([FromBody]RequestData request)
{
}
like image 156
Alex Riabov Avatar answered Oct 20 '25 06:10

Alex Riabov