加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:15:59 所属栏目:百科 来源:网络整理
导读:我有一个控制器有几个动作.如果服务上的IsCat字段为false,则应重定向Action: 所以这样的事情: public ActionResult MyCatAction() { if (MyService.IsCat==false) return RedirectToAnotherControllerAction(); ... 这可以在属性中完成并应用于整个Control
我有一个控制器有几个动作.如果服务上的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
     ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读