Access Request.Cookies from the controller constructor

I use the UserData property for FormsAuthenticationTicket to store specific information about a specific user. I have a HelperClass that deserializes this UserData into a user object for strongly typed access. I have a controller setup as follows

public class SomeController : Controller { private CookieData _cookieData; public SomeController() { _service = new ForderungsStellerService(new ModelStateWrapper(this.ModelState)); HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); _cookieData= GetSessionData.FromCookie(ticket); } } 

It seems that the problem is that Request is null at controller build time. When accessing Request.Cookies from ActionMethod, this snippet works.

I would like the _cookieData object to be populated inside the constructor for DRY reasons.

Does anyone have a hint of this problem?

Best wishes...

+4
source share
3 answers

I would create a ModelBinder that understands CookieData and how to get it from the Request object. I am afraid that the unit test code is needed to make the constructor happy. If you accept it as a parameter for the controller using the Binder module, you can avoid this overhead.

 public class SomeController : Controller { // only need to pass in the data object for unit testing. // ModelBinder takes care of DRY public ActionResult Index(CookieData cookieData) { } } 

The answer to why it does not work in the constructor is that the controller was not initialized with the ControllerContext at this point.

 public HttpContextBase HttpContext { get { return ControllerContext == null ? null : ControllerContext.HttpContext; } } 

If you really want to do this in the constructor (don't use), use HttpContext.Request instead of a wrapper. But by doing this, you will make your code unstable, and your alignment will decrease by 3 points.

+6
source

Override Controller.Initialize ():

 protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); // do further initialization here } 

Properties, such as Request, etc., will be available to you after calling base.Initialize ().

+5
source

It’s good to be dry, but in the case of ASP.NET MVC it ​​most often uses the use of a custom filter attribute or, like talljoe, demonstrates model binding.

  public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpCookie cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); filterContext.ActionParameters["CookieData"] = GetSessionData.FromCookie(ticket); base.OnActionExecuting(filterContext); } 
0
source

Source: https://habr.com/ru/post/1286330/


All Articles