1.应用程序级别设置
我们需要在 ConfigureServices方法中添加如下代码,设置文件上传的大小限制为60 MB。
public void ConfigureServices(IServiceCollection services)
{
services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = 60000000;
});
}
2.Action级别设置
除了上面对全局进行设置外,我们也可以通过自定义Filter的方式,对单个Action进行控制,Filter代码如下:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class RequestFormSizeLimitAttribute : Attribute, IAuthorizationFilter, IOrderedFilter
{
private readonly FormOptions _formOptions;
public RequestFormSizeLimitAttribute(int valueCountLimit)
{
_formOptions = new FormOptions()
{
ValueCountLimit = valueCountLimit
};
}
public int Order { get; set; }
public void OnAuthorization(AuthorizationFilterContext context)
{
var features = context.HttpContext.Features;
var formFeature = features.Get<IFormFeature>();
if (formFeature == null || formFeature.Form == null)
{
// Request form has not been read yet, so set the limits
features.Set<IFormFeature>(new FormFeature(context.HttpContext.Request, _formOptions));
}
}
}
因为ASP.NET Core MVC中,与之前版本不同的是具体功能被封装在了各种Feature(特征)中,HttpContext上下文只是能各个特征进行管理的容器。这个Filter中就只将Action拦截,对HttpContext中的FormFeature(负责表单提交功能)重新进行设置,从而达到限制具体Action上传文件大小的目的。
本文转自 zddnd 51CTO博客,原文链接:http://blog.51cto.com/13013666/1939708