ASP.NET 使用 DisableRequestSizeLimit 的核心测试方法

ASP.NET Core test method with DisableRequestSizeLimit

我有一个ASP.NET核心项目,用这个方法:

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

我推送方法后,性能测试失败,因为他在请求中发送了非常大的文件。

所以我在方法中添加了DisableRequestSizeLimit

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

现在,我想为这个错误编写一个测试。

如何伪造一个非常大的请求?

使用RestSharp nuget 包编写此类测试非常方便。您的测试将向您的 Asp.net core 应用发出真正的 http 请求:

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

顺便说一句,默认情况下 asp.net 核心应用程序 has 28.6 MB 请求大小限制。您可以通过 [DisableRequestSizeLimit] 禁用它(就像您所做的那样),然后您可以使用任何负载大小发出请求,但这通常是一种不受欢迎的行为。然后,可能最好使用 [RequestSizeLimit(50_000_000)] 将默认限制更改为所需的值。

也许您没有达到请求大小限制,而是达到了表单大小限制;请尝试 RequestFormLimits(MultipartBodyLengthLimit=Int32.MaxValue)。 请注意 MultipartBodyLengthLimit 是长型,考虑到您的情况,我认为完全填写表格大小限制是公平的。