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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With