There is a need to deny requests that have ANY body contents (meaning that body
size is > 0). I tried using RequestSizeLimit
attribute but it does not seems to be working properly.
Code:
[HttpPost]
[RequestSizeLimit(0)]
public IActionResult Test()
{
return Ok();
}
I am using Postman
for tests. Provide "qwerty" as a value for body of POST
request. Here is what Kestrel
log looks like:
info: Microsoft.AspNetCore.Server.Kestrel[17] Connection id "0HLN06I1687S4" bad request data: "Request body too large." Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Request body too large. at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1MessageBody.ForContentLength.OnReadStarting() at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.TryStart() at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.ConsumeAsync() at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication 1 application) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication 1 application)
Despite this - I still see a 200 (OK) response. I can debug into the method without any issues. It seems like - filter is working fine - but for some reason it it not triggering exceptions. The expected behavior - is "payload too large" (413) status returned for the request and the code execution in method not triggered.
Any ideas or explanation - why I am seeing this behavior?
This is not an answer to a question, but a solution to my problem. I have written my own implementation of an action filter that is working as expected.
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
};
}
}
}