first English is not my first language but i will do my best ...

i have spend more than one hour to figure-out how to apply maxRequestLength in a web.config for a specific view with meany route ...

here is my routes:

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

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

I want to allow upload of 200Mb on only specific action/view and not in all the application. Some time, the same view have different url, like the view Item can be called by AddItem and EditItem.

i was hopping i can set this using attribute, like [AllowUpload(200)] so i have try it but this setting is evaluated before the attribute in MVC.

what i'm trying to do is to set the max on the web.config and register a filter attribute to deny the action in the Custom Attribute. controller will look like this :

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

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

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

}

I don't know how to do this attribute and how the controller attribute will be overridden by the action attribute.

the best way i can imagine is the attribute because i will have different upload right on meany views who can have different actions, but if you have an idea, a plugin or any-thing else, please tell me.

tank you very mush

有帮助吗?

解决方案

I have finally found how to do this.

i set the max value on webconfig, and add an ActionFilterAttribute to each controller.

the only thing i need to be sure is to always check ModelState.IsValid in controller's actions.

here is the attribute code:

[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;
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top