2010-05-24 58 views
1

如何在asp.net mvc中使用自定義過濾器處理Application_BeginRequest?如何在asp.net mvc中僅更改一個路由的會話?

我想只爲一條路由(〜/ my-url)恢復會話。

這將是很酷,如果我可以創建一個自定義過濾器並處理它。

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     var context = HttpContext.Current; 

     if (string.Equals("~/my-url", 
      context.Request.AppRelativeCurrentExecutionFilePath, 
      StringComparison.OrdinalIgnoreCase)) 
     { 
      string sessionId = context.Request.Form["sessionId"]; 

      if (sessionId != null) 
      { 
       HttpCookie cookie = context.Request.Cookies.Get("ASP.NET_SessionId"); 
       if (cookie == null) 
       { 
        cookie = new HttpCookie("ASP.NET_SessionId"); 
       } 
       cookie.Value = sessionId; 
       context.Request.Cookies.Set(cookie); 
      } 
     } 
+0

可能的解決方案: http://weblogs.asp.net/imranbaloch/archive/2010/04/05/reading-all-users-session.aspx – 2010-05-27 01:13:08

回答

2

我是用IRouteHandler做的。

public class SessionHandler : IRouteHandler 
{ 
    public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext) 
    { 
     string sessionId = requestContext.HttpContext.Request.Form["sessionId"]; 

     if (sessionId != null) 
     { 
      HttpCookie cookie = requestContext.HttpContext.Request.Cookies.Get("ASP.NET_SessionId"); 
      if (cookie == null) 
      { 
       cookie = new HttpCookie("ASP.NET_SessionId"); 
      } 
      cookie.Value = sessionId; 
      requestContext.HttpContext.Request.Cookies.Set(cookie); 
     } 


     return new MvcHandler(requestContext); 
    } 
} 

這是在Global.asax中(ABC/QWR是路線):

RouteTable.Routes.Add(new Route(
       "abc/qwr", 
       new RouteValueDictionary(new {controller = "MyController", action = "MyAction"}), 
       new RouteValueDictionary(), 
       new RouteValueDictionary(new { Namespaces = new[] { typeof(MyControllerController).Namespace } }), 
       new SessionHandler() 
     )); 

有何評論?