Home > Mobile >  asp.net core, limit MaxRequestBodySize for each API call
asp.net core, limit MaxRequestBodySize for each API call

Time:07-14

I like to set the MaxRequestBodySize for an API operation depending on a query string parameter when API operation is called.

Let's say, something like that:

    [HttpPost("{para1}")]
    [RequestSizeLimit(...when para1 = "a" ? 500MB : 50MB)]
    public void PostIt(string para1, [FromBody] string bodyContent)
    {
        // do stuff
    }

However, with the RequestSizeLimit attribute this cannot be done, I guess somhow with the middleware it should be possible, but I have to admit, have not found any working solution so far.

Is this technically even possible and how can I achieve the goal?

I'm using .net 6.0

CodePudding user response:

If you want to set the MaxRequestBodySize for an API operation, using RequestSizeLimit is right choice. But usually argument should be numbers. For example, this following code would allow PostIt to accept request bodies up to 30,000,000bytes.

[HttpPost]                                     
[RequestSizeLimit(30_000_000)]                   
public void PostIt(string para1, [FromBody] string bodyContent)                        
{

I see you mentioned the middleware here, if the request is not working by an MVC action, the limit can still be modified by using the IHttpMaxRequestBodySizeFeature. For example:

app.Run(async context =>                                                               
{                                   
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 30_000_000;

Using the middleware or not, the argument should be a number. So I suggest writeing a function to finish your goal and then return a number as the argument.

  • Related