开发者

How to change Session for only one route in asp.net mvc?

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["session开发者_运维知识库Id"];

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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜