I want to use the Request, Response properties of System.Web.Mvc.Controller class to set and read cookies in the HTTP request and response. The reason to do so is – it obviates the need for writing utility classes that read from requests and populate data in some helper class. I can push all such code in custom base controller (from which all my controllers are derived from).
So I have got following code in my `BaseController’
if (Request != null)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
HttpContext.User = new GenericPrincipal(new GenericIdentity(authCookie.Value), null);
Thread.CurrentPrincipal = HttpContext.User;
}
}
but the Request is always null. How is this populated?
If you have this code in the constructor of your base controller then it is normal. You need to put it in the Initialize method. Also what you are doing shouldn’t be done in a controller. Looking at your code you seem to be populating the HttpContext.User property: this should be done in a custom Authorize action filter.
For example:
and then decorate your base controller with this attribute:
Notice that this attribute requires the user to be authenticated in order to give access to the corresponding action so use it only on controllers/actions that require authentication.