3

I have a controller which contains different methods. How can I define specific request size limit for each method?

I've tried these links, but I don't want to define a global size in web.config or startup

Asp.net Core 2.0 RequestSizeLimit attribute not working

Asp.net Core RequestSizeLimit still executes action

HTTP Error 404.13 - asp.net core 2.0

Increase upload file size in Asp.Net core

[HttpPost]
[RequestSizeLimit(1000000)]
public void MyMethod1([FromBody] string value)
{
 // Do something
}

[HttpPost]
[RequestSizeLimit(2000000)]
public void MyMethod2([FromBody] string value)
{
 // Do something else
}

I expect MyMethod1 accepts only requests with size less than 1000000 bytes and MyMethod2 accepts requests with size less than 2000000 bytes. But this does not work and they accept requests with any size. What is the issue here?

Mohammad Taherian
  • 1,622
  • 1
  • 15
  • 34
  • Is there any demo to reproduce your issue? How large value did you send? I made a test with built-in asp.net core 2.2 mvc template and your code with `[RequestSizeLimit(3)]`, it returns correctly with `BadHttpRequestException: Request body too large.` – Edward Aug 30 '19 at 06:01
  • @TaoZhou for the first one I tried with 1.5MB request body and the second one 2.3MB request body which was raw text. But it entered to method and did not response with `BadHttpRequestException: Request body too large` – Mohammad Taherian Aug 30 '19 at 12:35
  • Could you try to make a test with `[RequestSizeLimit(3)]`? Is there any demo to reproduce your issue? – Edward Sep 02 '19 at 01:47
  • @TaoZhou I just created a new web API project in visual studio and in controller set those `RequestSizeLimit` to action methods. – Mohammad Taherian Sep 03 '19 at 15:52

1 Answers1

1

That solution you tested its used for MVC not .Net Core

What I Found mostly people using solution (Global Solution) in the below:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
     .UseStartup<Startup>()
      .UseKestrel(options =>{
       options.Limits.MaxRequestBodySize = 52428800; //50MB
       });
}

but it have different ways for it like MiddleWare like below:

  app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), 
        appBuilder =>{
        context.Features.Get<IHttpMaxRequestBodySizeFeature> 
        ().MaxRequestBodySize = null;
        //TODO: take next steps
  });

Sorry For My Bad English :)

Source => Helper Link

Ramin Azali
  • 198
  • 11