c# - 当全局注册操作过滤器时跳过特定操作的过滤器

标签 c# asp.net-mvc-4 asp.net-web-api

我已经编写了自己的 Action 过滤器并在 global.asax 文件中注册,现在我的问题是如何跳过 这个用于特定操作的过滤器,我通过为例如 DontValidate 创建自定义属性来考虑这个 并将它放在我想跳过验证的操作上,在我的操作过滤器代码中,我将设置一个条件,如果操作包含 DontValidate 属性然后跳过验证。所以目前我不知道如何 实现它:

下面的代码是我的验证操作过滤器

   public class ValidationActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.Request.Method.ToString() == "OPTIONS") return;
            //bool dontValidate =  context.ActionDescriptor. // here im stuck how to do
            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                JsonValue errors = new JsonObject();
                foreach (var key in modelState.Keys)
                {
                    // some stuff
                }

                context.Response  = context.Request.CreateResponse<JsonValue>(HttpStatusCode.BadRequest, errors);
            }
        }
    }

最佳答案

您可以从上下文的 ActionDescriptor 属性中获取用于装饰 Controller 操作的属性列表:

public class ValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        if (context.ActionDescriptor.GetCustomAttributes<DontValidateAttribute>().Any())
        {
            // The controller action is decorated with the [DontValidate]
            // custom attribute => don't do anything.
            return;
        }

        if (context.Request.Method.ToString() == "OPTIONS") return;
        var modelState = context.ModelState;
        if (!modelState.IsValid)
        {
            JsonValue errors = new JsonObject();
            foreach (var key in modelState.Keys)
            {
                // some stuff
            }

            context.Response = context.Request.CreateResponse<JsonValue>(HttpStatusCode.BadRequest, errors);
        }
    }
}

关于c# - 当全局注册操作过滤器时跳过特定操作的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12891115/

相关文章:

asp.net - 如何通过@Html.DropDownListFor正确设置选定状态

.net - Postman 客户端凭据流与 Azure AD 保护资源

c# - 在.net webApi中删除没有id参数的请求

c# - 从 WebAPI Controller 返回 DTO

c# - 使用 Catel 命令在 CanExecuteChanged 上发生内存泄漏

c# - 多线程错误 : There is already an open DataReader associated with this Connection which must be closed first

javascript - 简单的 Javascript If 语句在 ASP.NET MVC View 中不起作用

mysql - 无法找到包 '6.9.5.0' 的版本 'MySql.Data.Entity.EF6'

c# - MVC4 应用程序尝试引用较新版本的 System.Web.WebPages.Razor 时出现问题

c# - 正则表达式匹配以某个字符结尾但不以另一个字符开头且中间有空格的字符串