c# - asp.net core 5.0 RequestSizeLimit 不起作用

标签 c# asp.net-core .net-5

我正在使用 ASP.net core 5.0,但 RequestSizeLimit 似乎不起作用。

我有以下 Controller

[HttpPost("addfile")]
[RequestSizeLimit(5_242_880)] // 5MB
public IActionResult AddFile([FromBody] IFormFile file)

现在,当我想测试所述 Controller 时,我创建一个 IFormFile ,如下所示:

public static Mock<IFormFile> TestFile(string filename, string content)
{
    var fileMock = new Mock<IFormFile>();

    var ms = new MemoryStream();
    var writer = new StreamWriter(ms);
    writer.Write(content);
    writer.Flush();
    ms.Position = 0;
    fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
    fileMock.Setup(_ => _.FileName).Returns(filename);
    fileMock.Setup(_ => _.Length).Returns(ms.Length);

    return fileMock;
}

在我的测试中,我现在添加 50MB 的内容,如下所示:

var bigContent = RandomString(50 * 1024 * 1024);
var testFile = TestFile("calendar.ical", bigContent);
...
var result = controller.AddFile(testFile.Object);

信息:RandomString 返回给定长度的字符串(不是最优化的方式):

public static string RandomString(int length)
{
    StringBuilder builder = new StringBuilder();
    Random random = new Random();
    char ch;
    for (int i = 0; i < length; i++)
    {
        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
        builder.Append(ch);
    }
    return builder.ToString();
}

我期望状态代码不是 200 - 好的。 我做错了什么吗?

最佳答案

您正在对 Controller 进行单元测试 - 不幸的是,[RequestSizeLimit] 属性是作为请求管道中的过滤器实现的 - 并且过滤器不会作为单元测试的一部分运行。

这是描述的in the docs .

Set up unit tests of controller actions to focus on the controller's behavior. A controller unit test avoids scenarios such as filters, routing, and model binding. Tests that cover the interactions among components that collectively respond to a request are handled by integration tests. For more information on integration tests, see Integration tests in ASP.NET Core.

有关集成测试的更多信息,请访问 here .

关于c# - asp.net core 5.0 RequestSizeLimit 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65587598/

相关文章:

c# - 非管理员用户单击关联文件时仅传递 1 个参数

c# - 隐藏基类或接口(interface)以免污染代码

c# - .NET5 JsonPatchDocument.ApplyTo 在添加或替换时抛出

c# - 引用 .Net Core 3.1 NuGet 包的 .Net 5 Visual Studio 项目/解决方案如何成功编译?

c# - 手动添加迁移?

c# - webkit-sharp 滚动到 HTML anchor 标记

asp.net-core - asp.net 核心直播 mp4 流媒体

c# - 如何调用另一个文件夹中的 View

c# - ASP.NET 5 身份 - 自定义 SignInManager

.net - ASP.NET Core (.NET 5) + Angular 11 = 在空项目上构建错误