views:

103

answers:

1

How to handle Application_BeginRequest using a custom filter in asp.net mvc?

I want to restore session only for one route (~/my-url).

It would be cool, if I could create a custom filter and handle that.

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);
            }
        }
+2  A: 

I did it using 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);
    }
}

This is in global.asax (abc/qwr is the route):

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()
        ));

Any comments?

denis_n