How to set a default initialization cookie in ASP.NET MVC
I was wondering if anyone can shed some light on cookie management. More precisely I would like to know how I could set up an initial cookie/s when a user start a session in a website.
Currently the ASP.NET_SessionId cookie
is located on user computers when they navigate to the domain. I would like to set up an additional cookie with details of lan开发者_Python百科guageid
and countryid
with default parameters the first time the user navigate to the site.
Do anyone knows if there is any technique to do this, such as through web.config set up or placing cookie details using layout.cshtml like
Response.Cookies["language"].Value = "1";
Response.Cookies["country"].Value= "7";
or similar?, any option will be appreciated.
You could do this in an action filter:
public class LocalizationAwareAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var httpContext = filterContext.HttpContext.Current;
if (!httpContext.Cookies.Keys.Contains("language"))
{
httpContext.Response.AppendCookie(new HttpCookie("language", 1));
}
if (!httpContext.Cookies.Keys.Contains("country"))
{
httpContext.Response.AppendCookie(new HttpCookie("country", 7));
}
}
}
The filter can be applied globally, so you don't have to worry about remembering it on each action method or controller.
I haven't worked much with cookies in ASP.NET MVC, but the way I'd do it would be to have a little block of code in Global.asax or a separate base controller that gets executed on every request. This code would check the HttpContext for the existence of such a cookie, and if it didn't exist, it would create one. I'll work up a code sample and will update this answer soon.
精彩评论