有必要拒绝具有任何身体内容的请求(这意味着body
大小为> 0(。我尝试使用RequestSizeLimit
属性,但似乎无法正常工作。
代码:
[HttpPost]
[RequestSizeLimit(0)]
public IActionResult Test()
{
return Ok();
}
我正在使用Postman
进行测试。提供" QWERTY"作为POST
请求主体的值。这是Kestrel
日志的样子:
信息:microsoft.aspnetcore.server.kestrel [17] 连接ID" 0HLN06I1687S4"不良请求数据:"请求实体太大。" microsoft.aspnetcore.server.kestrel.core.badhttprequestexception: 请求身体太大。在 microsoft.aspnetcore.server.kestrel.core.badhttprequestexception.throw(requestReptivectionReason 原因( microsoft.aspnetcore.server.kestrel.core.internal.http.http1messagebody.forcontentlength.onreadstarting(( 在 microsoft.aspnetcore.server.kestrel.core.internal.http.messagebody.trystart(( 在 microsoft.aspnetcore.server.kestrel.core.internal.http.messagebody.consumeasync(( 在 microsoft.aspnetcore.server.kestrel.core.internal.http.httpprotocol.processrequests [tcontext](ihttppapplication 1( 应用程序( microsoft.aspnetcore.server.kestrel.core.internal.http.httpprotocol.processrequestsasync [tcontext](ihttppapplication 1 应用程序(
尽管如此 - 我仍然看到200(确定(的响应。我可以在没有任何问题的情况下进行调试。似乎 - 过滤器工作正常 - 但是由于某些原因,它没有触发异常。预期的行为 - 是"有效负载太大"(413(为请求返回的状态,而未触发的方法执行代码执行。
有任何想法或解释 - 我为什么看到这种行为?
这不是问题的答案,而是解决我问题的方法。我已经写了自己的操作过滤器的实施。
public class PayloadMaximumSizeFilter : ActionFilterAttribute
{
private long _maxContentLength;
private string _message;
public PayloadMaximumSizeFilter(long maxContentLength)
{
this._maxContentLength = maxContentLength;
}
public PayloadMaximumSizeFilter(long maxContentLength, string message)
{
this._maxContentLength = maxContentLength;
this._message = message;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
long? contentLength = filterContext.HttpContext.Request.ContentLength;
if (contentLength.HasValue && contentLength.Value > _maxContentLength)
{
filterContext.Result = new JsonResult(filterContext.ModelState)
{
Value = _message ?? "Request body too large.",
StatusCode = 413
};
}
}
}