简体   繁体   中英

Asp.Net MVC 4 - ActionFilterAttribute Usage

I writted this code (CustomHandle) for application log. But, i don't want to run this code on some actions.

CustomHandle.cs:

public class CustomHandle: ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        string FormVeri = "";
        string QueryVeri = "";
        foreach (var fName in filterContext.HttpContext.Request.Form)
        {
            FormVeri += fName + "= " + filterContext.HttpContext.Request.Form[fName.ToString()].ToString() + "& ";
        }
        foreach (var fQuery in filterContext.HttpContext.Request.QueryString)
        {
            QueryVeri += fQuery + "= " + filterContext.HttpContext.Request.QueryString[fQuery.ToString()] + "& ";
        }

        base.OnResultExecuted(filterContext);
    }
}

FilterConfig.cs:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CustomHandle());
    }
}

HomeController.cs:

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

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


CustomHandle works on Index and Login . But, CustomHandle is i don't want run on Login ActionResult .

Thanks,
Best Regards.

In MVC 5... instead of adding the action filter in FilterConfig.cs

  • add it to each Controller (or a base controller) - all actions will be affected.
  • use [OverrideActionFilter] to remove that filter for a specific action.

Example

    [CustomHandle]
    public class AnyController : Controller
    {
        public ActionResult Index()      // has [CustomHandle] attribute
        {
        }

        [OverrideActionFilter]
        public ActionResult Login()      // ignores the [CustomHandle] attribute
        {
        }
    }

When a filter is injected into a controller class, all its actions are also injected. If you would like to apply the filter only for a set of actions, you would have to inject [CustomActionFilter] to each one of them:

[CustomHandle]
public ActionResult Index()
{
  ...
}

public ActionResult Login()
{
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM