【问题标题】:How to get redirect to a specific url from basecontroller如何从 basecontroller 重定向到特定的 url
【发布时间】:2013-10-14 11:44:52
【问题描述】:

我有 HomeController 和 BaseController 以及 BaseController 中的一个方法,我需要从中重定向到特定的 URL。

这里是代码:-

public class HomeController : BaseController
{
    public ActionResult Index()
    {
       VerfiySomething();

       CodeLine1.....
       CodeLine2.....
       CodeLineN.....
    }
}

这里是基本控制器 -

public class BaseController : Controller
{
    public void VerfiySomething()
    {
       if(based_on_some_check)
       {
           Redirect(myurl);
       }
    }
}

但是即使在 BaseController 中执行“Redirect(myurl)”后,codeline1,2...N 也会在 HomeController 中执行

我想要的是它应该重定向到其他 URL(而不是任何其他操作)而不执行 CodeLin1,2...N

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    我会实现一个ActionFilterAttribute。

    见:Redirect From Action Filter Attribute

    public class VerifySomethingAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (based_on_some_check)
            {
                filterContext.Result = new RedirectResult(url);
            }
    
            base.OnActionExecuting(filterContext);
        }
    }
    

    用法:

    [VerifySomething]
    public ActionResult Index()
    {
        // Logic
    }
    

    【讨论】:

      【解决方案2】:

      您可以在控制器的虚拟方法OnActionExecuting 中验证某些内容:

      class BaseController : Controller
      {
          protected override void OnActionExecuting(ActionExecutingContext context)
          {
              if (somethingWrong)
              {
                  context.Result = GetSomeUnhappyResult();
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-05
        • 1970-01-01
        • 1970-01-01
        • 2015-07-31
        • 2018-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多