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
     ...
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...