【问题标题】:asp.net MVC5 C# Specific upload limit by action/controllerasp.net MVC5 C# 动作/控制器的特定上传限制
【发布时间】:2014-03-13 05:33:10
【问题描述】:

第一英语不是我的第一语言,但我会尽力而为......

我已经花了一个多小时来弄清楚如何在 web.config 中应用 maxRequestLength 以获取具有平均路线的特定视图...

这是我的路线:

/{Controller}/{Action}/{id}

/{CategoryId}/{Controller}/{Action}/{id}

我希望仅允许在特定操作/视图上上传 200Mb,而不是在所有应用程序中。有时候,同一个视图有不同的url,比如视图Item可以被AddItem和EditItem调用。

我在跳跃,我可以使用属性设置这个,比如 [AllowUpload(200)] 所以我已经尝试过了,但是这个设置是在 MVC 中的属性之前评估的。

我要做的是在 web.config 上设置最大值并注册一个过滤器属性以拒绝自定义属性中的操作。控制器将如下所示:

[AllowUpload(1)]
public class MyController : Controller
{

    public ActionResult Index()
    {return View();}

    [AllowUpload(200)]
    public ActionResult Upload()
    {return View();}

}

我不知道如何做这个属性以及控制器属性将如何被操作属性覆盖。

我能想象的最好的方法是属性,因为我将在可能有不同操作的卑鄙视图上拥有不同的上传权,但如果你有想法、插件或其他任何东西,请告诉我。

你太难了

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 web-config custom-attributes


    【解决方案1】:

    我终于找到了方法。

    我在webconfig上设置了最大值,并为每个控制器添加了一个ActionFilterAttribute。

    我唯一需要确定的是始终在控制器的操作中检查 ModelState.IsValid。

    这里是属性代码:

    [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
    public sealed class UploadActionAttribute : ActionFilterAttribute
    {
        public UploadActionAttribute(double maxMb = 4d)
        {
            MaxMb = maxMb;
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (ConvertBytesToMegabytes(filterContext.HttpContext.Request.ContentLength) > MaxMb)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult() { Data = new { Success = false, MaxContentLengthExceeded = true } };
                }
                else
                    filterContext.Controller.ViewData.ModelState.AddModelError("", string.Format(CSRess.MaxRequestLengh, MaxMb));
            }
            base.OnActionExecuting(filterContext);
        }
    
        private double MaxMb { get; set; }
        static double ConvertBytesToMegabytes(long bytes)
        {
            return (bytes / 1024f) / 1024f;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多