如何创建自定义的操作筛选器,该操作筛选器将检查ModelState是否有效,如果无效,则将ModelState错误返回到同一视图? 我要编写一个自定义操作筛选器,在所有POST请求之前,请确保该ModelState有效,并且如果ModelState无效,它将把ModelState错误返回到同一视图。
这是我的示例代码。但是我真的不知道如何将ModelState错误返回到同一视图。
namespace Site.Web.Infrastructures.CustomValidationAttribute
{
public class GlobalMvcValidateModelStateAttribute : ActionFilterAttribute
{
public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
List<string> list = (from modelState in context.ModelState.Values from error in modelState.Errors select error.ErrorMessage).ToList();
//Also add exceptions.
list.AddRange(from modelState in context.ModelState.Values from error in modelState.Errors select error.Exception.ToString());
context.Result = new BadRequestObjectResult(list);
}
return base.OnActionExecutionAsync(context, next);
}
}
}