设置视图特定的maxAllowedContentLength

时间:2016-04-20 21:19:52

标签: c# asp.net asp.net-mvc iis web-config

有没有办法拥有特定于视图的属性maxAllowedContentLength?

例如:假设我的mvc应用程序中有两个页面,我希望一个页面接受最大1 MB的Content-Length,我希望另一个页面接受最大10 MB的内容长度?

2 个答案:

答案 0 :(得分:1)

如果它们位于不同的目录中,您可以通过添加web.config文件为每个目录提供自己的maxAllowedContentLength。在子目录中,您只需添加与基本目录不同的值。

答案 1 :(得分:1)

您可以实现自定义ActionFilter

public class ContentLengthFilter : ActionFilterAttribute
{
    public ContentLengthFilter(int maxContentLength)
    {
        MaxContentLength = maxContentLength;
    }
    public int MaxContentLength { get; private set; }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.ContentLength > MaxContentLength)
            throw new InvalidOperationException();
        base.OnActionExecuting(filterContext);
    }
}

之后,将此属性应用于特定操作

[HttpPost]
[ContentLengthFilter(10000)]
public ActionResult UploadFile()
{
    var count = Request.Files.Count;