微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – ASP.Net MVC 4使用Attribute还是BaseController?

我有一个控制器有几个动作.如果服务上的IsCat字段为false,则应重定向Action:

所以这样的事情:

public ActionResult MyCatAction()
    {
        if (MyService.IsCat==false)
            return RedirectToAnotherControllerAction();
     ...

这可以在属性中完成并应用于整个Controller的一组操作吗?

解决方法

在这种情况下,Action filter是可行的方法

Action filter,which wraps the action method execution. This filter
can perform additional processing,such as providing extra data to the
action method,inspecting the return value,or canceling execution of
the action method.

这是一个很好的MSDN如何:How to: Create a Custom Action Filter

在你的情况下,你会有这样的事情:

public class RedirectFilterattribute : ActionFilterattribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (MyService.IsCat==false)
            return RedirectToAnotherControllerAction();
    }
}

然后,您将在控制器级别应用此过滤器(适用于所有控制器操作)

[RedirectFilterattribute]
public class MyController : Controller
{
   // Will apply the filter to all actions inside this controller.

    public ActionResult MyCatAction()
    {

    }    
}

或按行动:

[RedirectFilterattribute]
public ActionResult MyCatAction()
{
     // Action logic
     ...
}

原文地址:https://www.jb51.cc/csharp/239158.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐