我扩展了ActionFilterAttribute
类并覆盖了OnActionExecuting
,因此我可以全局捕获模型状态是否有效。但是,我想在某些控制器的某些方法中允许无效的模型状态。
我创建了一个自定义属性并将其放在Controller上,现在我能够看到控制器是否具有该属性(如果有,则不验证模型状态)。但我想将属性放在控制器中的方法上,所以我想知道如何从ActionExecutingContext
访问方法(或委托对象)并查看它是否具有ExemptValidation
类型的属性
[Route("api/[controller]")]
[ExemptValidation] // works here
public class BadController : Controller
{
[ExemptValidation] // does not work here
public IActionResult GetValues()
{
return Ok("Good");
}
}
public class ModelStateValidationActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
var modelState = actionContext.ModelState;
// check if controller has attribute of type ExemptValidation
var prop = actionContext.Controller.GetType().GetCustomAttribute(typeof(ExemptValidation));
// if prop != null then ...
if (!modelState.IsValid)
{
actionContext.Result = new BadRequestObjectResult(new
{
ModelErrorState = modelState.Values.Where(state => state.ValidationState == ModelValidationState.Invalid)
});
return;
}
base.OnActionExecuting(actionContext);
}