C# 在模型绑定ASP.NET Web Api之前验证内容长度
我想知道如何在ASP.NET Web Api中的模型绑定器读取请求正文之前验证内容长度 我可以在动作中这样做,但是这是一种资源浪费,因为流已经被读取了C# 在模型绑定ASP.NET Web Api之前验证内容长度,c#,asp.net,asp.net-mvc,asp.net-web-api,C#,Asp.net,Asp.net Mvc,Asp.net Web Api,我想知道如何在ASP.NET Web Api中的模型绑定器读取请求正文之前验证内容长度 我可以在动作中这样做,但是这是一种资源浪费,因为流已经被读取了 var contentLength = Request.Content.Headers.ContentLength; if (contentLength > 1024*1024*20) { throw new HttpResponseException(HttpStatusCode.RequestEntityTooLarge);
var contentLength = Request.Content.Headers.ContentLength;
if (contentLength > 1024*1024*20)
{
throw new HttpResponseException(HttpStatusCode.RequestEntityTooLarge);
}
可以在操作筛选器中执行此操作吗?如果您正在使用Owin托管API,并且您希望将此限制全局应用于所有请求,则可以在Owin管道中Web API之前执行的简单Owin中间件中执行此检查:
app.Use(async (c, n) =>
{
var request = c.Request;
if (request != null)
{
string[] headerValues;
if (request.Headers.TryGetValue("Content-Length", out headerValues))
{
var lengthValue = headerValues.First();
if (Convert.ToInt64(lengthValue) > 1024 * 1024 * 20)
{
c.Response.StatusCode = (int)HttpStatusCode.RequestEntityTooLarge;
return;
}
}
}
await n.Invoke();
});
//app.UseWebApi(..)
[编辑]
如果需要以更精细的方式限制内容长度
,那么最好的选择是创建一个授权过滤器
,该过滤器在模型绑定之前执行,而不是一般的操作过滤器
像这样的方法应该会奏效:
public class MaxContentLengthAttribute : AuthorizationFilterAttribute
{
private readonly long _maxContentType;
public MaxContentLengthAttribute(long maxContentType)
{
_maxContentType = maxContentType;
}
public override void OnAuthorization(HttpActionContext actionContext)
{
var contentLength = actionContext.Request.Content.Headers.ContentLength;
if (contentLength.HasValue && contentLength.Value > _maxContentType)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.RequestEntityTooLarge);
}
}
}
在控制器中:
[MaxContentLength(1024*1024*20)]
public void Post([FromBody]Foo value)
{
DoWork(value);
}
通过这种方式,您可以在模型绑定器读取内容之前响应请求。请求对象可能已经由框架填充。因此,在应用任何筛选器之前,它会设置请求对象的所有属性。您可以通过实现IActionFilter来编写逻辑。不使用Owin,我不希望它被全局应用,只需特定于操作。