如何在MVC控制器的helper类中执行Redirect?

时间:2012-10-26 22:55:28

标签: c# asp.net-mvc

我有一些在多个控制器操作开始时运行的常用代码。我想将该代码重构为静态类,以促进该代码块的重用。

代码检查变量,查找cookie,如果满足条件,代码应该重定向到另一个页面(控制器/动作)。

问题是一切正常(包括cookie查找)但重定向不会触发。代码通过重定向,重定向永远不会发生。

在帮助程序类中重定向的正确方法是什么?

现在是代码:

此行不起作用: myController.HttpContext.Response.Redirect(redirectURL);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyProject.WebUI
{
    public static class SessionValidationHelper
    {
        // helper class to encapsulate common routines to check for missing session data
        public static void SessionIdRequired(string id, Controller myController)
        {
            if (id == null || id == "")
            {
                // check cookie
                if (myController.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("cookiename"))
                {
                    // if a session cookie was found, send to the registration recovery page
                    string sessionGuidCookieValue = "";
                    sessionGuidCookieValue = myController.ControllerContext.HttpContext.Request.Cookies["cookiename"].Value;

                    // check if GUID/SessionID exists in persistent cache

                    // send to Session Recovery
                    //myController.HttpContext.Response.RedirectToRoute("SessionRecovery", new { Controller = "SessionRecovery", Action = "Index", id = sessionGuidCookieValue });
                    string redirectURL = @"~/SessionRecovery/Index/" + sessionGuidCookieValue;

                    // this code isn't working
                    myController.HttpContext.Response.Redirect(redirectURL);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以创建一个属性作为过滤器并使用它来装饰操作: (我已将您提供的代码放在属性中)

public class SessionValidationAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
       if (filterContext.Result == null)
       {
          var id = filterContext.RouteData.Values["id"] as string;
          if (id == null || id == "")
          {
            // check cookie
            if (filterContext.Controller.ControllerContext
               .HttpContext.Request.Cookies.AllKeys
               .Contains("cookiename"))
            {
                // if a session cookie was found,
                // send to the registration recovery page
                string sessionGuidCookieValue = "";
                sessionGuidCookieValue = filterContext.Controller
                    .ControllerContext.HttpContext.Request
                    .Cookies["cookiename"].Value;

                // check if GUID/SessionID exists in persistent cache

                // send to Session Recovery
                string redirectURL = @"~/SessionRecovery/Index/"
                        + sessionGuidCookieValue;

                // this code isn't working
                filterContext.Result = new RedirectResult(redirectURL);
            }
          }
       }
    }

    public abstract bool CanAccessResource(User user);
}

在你的行动中你这样做:

[SessionValidationAttribute]
public ActionResult MyAction()
{
     // code of the action
}

或者如果您想将它应用于类中的所有操作:

[SessionValidationAttribute]
public class MyController : Controller
{
     // code of the class, containing all actions
}

或者如果你想全局应用(请小心): 在您的Application类(继承System.Web.HttpApplication的类)中,您可以执行此操作:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalFilters.Filters.Add(new SessionValidationAttribute());

        // register routes
    }
}