我正在使用 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/