Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a cookie for every visitor to my asp.net MVC site?

I'm experimenting with an ASP.NET MVC 3 site, using razor as the view-engine. I need to assign a cookie to every visitor of my site. What would be the best place/way to do this? Please elaborate, because I'm very new at ASP.NET.

like image 292
Erik Oosterwaal Avatar asked Dec 04 '22 21:12

Erik Oosterwaal


1 Answers

There are 3 ways to implement it without breaking mvc pattern:

1 - Base controller class with specified behaviour at OnActionExecuting / OnActionExecuted / OnResultExecuting method (if this behavior is necessary across the entire web site)

2 - Create action filter with specified behaviour at OnActionExecuting / OnActionExecuted / OnResultExecuting methods:

public class MyCookieSettingFilterAttribute : ActionFilterAttribute 
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(name, value));
    }
}

and

assign filter attribute to some controllers/actions (if this behavior is not necessary for all web site), for example

[MyCookieSettingFilter]
public class MyHomeController : Controller
{
}

or

public class MyAccountController : Controller
{
    [MyCookieSettingFilter]
    public ActionResult Login()
    {
    }
}

3 - Create action filter with specified behaviour at OnActionExecuting / OnActionExecuted / OnResultExecuting methods and register it at global.asax - it will work for all actions of all controllers (if this behavior is necessary for all web site)

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new MyCookieSettingFilterAttribute());
}

I don't recommend to use Base Controller way, because it less extensible than Global Filter way. Use different global filters for providing different independent global behaviors.

like image 107
Evgeny Levin Avatar answered Dec 29 '22 10:12

Evgeny Levin