简体   繁体   中英

ASP.NET Core test method with DisableRequestSizeLimit

I have an ASP.NET Core project, with this method:

public async Task<ActionResult<ResultDto>> StartReadFiles(
    [ModelBinder(typeof(JsonModelBinder))] RequestDto request,
    IFormFile file1,
    IFormFile file2
)

After I pushed the method, the performance test failed because he sends very large files in the request.

So I added DisableRequestSizeLimit to the method:

[DisableRequestSizeLimit]
public async Task<ActionResult<ResultDto>> StartReadFiles(
    [ModelBinder(typeof(JsonModelBinder))] RequestDto request,
    IFormFile file1,
    IFormFile file2
)

And now, I want to write a test for this bug.

How can I fake the request with a very big body?

It is very convenient to write such tests using RestSharp nuget package. Your tests will make real http-requests to your Asp.net core app:

var client = new RestClient("http://path/to/api/");

var request = new RestRequest("resourceurl", Method.POST);

byte[] fileByteArray = new byte[50*1024*1024]; // 50 MB
request.AddFileBytes("file1", fileByteArray, "file1Name"); 

// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string

Btw, by default asp.net core app has 28.6 MB request size limit. You can disable it by [DisableRequestSizeLimit] (as you did) and then you can make request with any payload size, but it is usually an undesired behavior. Then, probably it is better to use [RequestSizeLimit(50_000_000)] to change the default limit to a desired value.

Maybe you are not hitting the request size limit but the form size limit; please try with RequestFormLimits(MultipartBodyLengthLimit=Int32.MaxValue) . Please note MultipartBodyLengthLimit is of long type and considering your case I think it is fair enough to full fill form size limit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM