【问题标题】:How to perform Redirect in helper class for MVC controller?如何在 MVC 控制器的帮助器类中执行重定向?
【发布时间】:2012-10-27 07:31:48
【问题描述】:

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

代码检查变量,查找 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);
                }
            }
        }
    }
}

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    您可以创建一个作为过滤器的属性并用它来装饰动作: (我已经把你提供的代码放在属性里了)

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

    【讨论】:

    • 这是一个很好的答案。实际上比第一个答案更完整,因为 var id = filterContext.RouteData.Values["id"] as string;对我来说是关键。
    猜你喜欢
    • 2011-06-26
    • 2015-10-28
    • 1970-01-01
    • 2015-04-11
    • 2020-10-30
    • 1970-01-01
    • 2017-08-21
    • 2013-10-21
    • 2016-12-20
    相关资源
    最近更新 更多