简体   繁体   中英

MVC adding a cookie at the entry point based on querystring

Got a scenario of cross-site availability of cookies (between desktop site and mobile site). When someone comes in as "http://www.xyz.com?qrystring=12345" OR "http://m.xyz.com?qrystring=12345" , I have to add a cookie for the domain (.xyz.com). Implemented it in the Asp.Net desktop app, but want to implement similar thing in Asp.Net MVC2 mobile site.

Any suggestions as to how to capture that from any page of the MVC mobile site. It can be any page on mobile site (m.xyz.com/page1?qrystring=1234) from which I should be able to add cookie. USING ASP.NET MVC2 and CAN'T USE MVC3

Can using Application_BeginRequest event in global.asax be safe with MVC app in this scenario?

you can write an actionrilter attribute and decorate your controller with it like

public class CookieStateAttribute : ActionFilterAttribute
    {
        string __key = "querystring";

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var viewData = filterContext.Controller.ViewData;
            var request = filterContext.HttpContext.Request;

            if (request.Cookies[__key] != null)
            {
                HttpCookie cookie = request.Cookies[__key];
                //do something with cookie value

            }
            else
            {
                var cookie = new HttpCookie(__key, "value");
                request.Cookies.Add(cookie);
            }
        }
    }

then you can decorate your controller with the attribute like

[CookieState]
public class HomeController:Controller
{
   .
   .
   .
}

Of course you will have to change implementation of the attribute according to your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM