1

I have a controller named BaseController, which is inherited by all other Controllers. I have a constructor of BaseController where I am doing some calculation on the basis of a variable patId which it picks from session and on the basis of this calculation user is allowed to perform some actions.

But there is a Controller MyController whose action receives this variable first time into this module from another application module so till then it is not set into the session.

public ActionResult MyAction(string patId)
{
  // First time patId is been set into session 

}

So my BaseController calculation is getting wrong for this action. Is there a way I can get this variable value into constructor of BaseController. So that I can check if session value is null then check for this parameter and set the session.

Please suggest if I can do this or I can solve out my issue from any another way.

prashant
  • 470
  • 3
  • 17
  • 1
    It is impossible to work around with just controller constructors. Cannot you just check if the value is available in session, and if it is not stop the calculation? Another option is to intercept all incoming requests and take the value from them, if needed, before it gets to controller, see [this thread](http://stackoverflow.com/q/11726848/728795) for ideas – Andrei Oct 14 '15 at 11:05
  • Thanks @Andrei .. It seems that it will help . I will try to opt second option and will give a try if that will help me or not – prashant Oct 14 '15 at 11:12
  • @Andrei , if I use ActionFilter to intercept the request, but the constructor of controller will be called first than the FilterAttribute. – prashant Oct 14 '15 at 11:25
  • well, i did not mean action filters approach from that thread, i thought that's obvious. others talk about http module and Application_BeginRequest, which should be more useful to you – Andrei Oct 14 '15 at 11:32

1 Answers1

1

Andrei comment helped me and I used thread mentioned by Andrei. There was discussed to intercept incoming request.There were two approaches that could help me were HttpModule and Application_BeginRequest and I opted for later.

But I did it in constructor of controller itself by intercepting http Request using HttpContext which is available in the constructor of controller as well.

public BaseController()
{
   // Check if variable exist in session
   // else check if patId is sent through request
   // then save it in session

   System.Web.HttpContext.Current.Session["PatId"] = System.Web.HttpContext.Request.Form["patId"];

   // perform remaining calculation
}
Community
  • 1
  • 1
prashant
  • 470
  • 3
  • 17