2
votes

I have 2 projects in my solution.

  1. MVC Web application
  2. Class library

    • The MVC Web application references the class library.
    • The class library contains a class that extends the default ASP.Net Controller.

I'm putting a variable in session in the application's Global.asax.

protected void Session_Start(object sender, EventArgs args)
{
   HttpContext.Current.Session["DomainName"] = Request.Url.Host;
}

In the class library I'm trying to get the value from the HttpContext.Session, but HttpContext.Session keeps coming up null.

public class MyController : System.Web.Mvc.Controller
{
    public MyController () : base()
    {
        //HttpContext.Session is always null at this point
        ViewData["DomainName"] = HttpContext.Session["DomainName"];
    } 
}

HttpContext.Current.Session doesn't seem to be an option in controllers. Any ideas?

4

4 Answers

3
votes

Two issues -- the HttpContext property in the Controller class is the current session. Unfortunately, it's not available in the constructor of the controller. Obviously because it's not passed in the constructor, it has to be set via the property afterwards. You might consider adding a property to hold the domain name and referencing the session from it -- that way it would be available for use when needed.

 protected string DomainName
 {
      get { return this.HttpContext.Session["DomainName"] as string; }
 }

The set it in ViewData in your actions or in OnActionExecuting/OnActionExecuted.

 protected override void OnActionExecuted( ActionExecutedContext context )
 {
      ViewData["DomainName"] = this.HttpContext.Session["DomainName"];
      // or ViewData["DomainName"] = this.DomainName;  // if you used the property
 }
1
votes

If you're just trying to add ViewData from the session, try doing it in the OnActionExecuting method. This is where I typically add ViewData I want for every View.

0
votes

You just use Session by itself (it's a property of Controller), but that just maps to Controller.HttpContext.Session (in other words, what you're already using), so it won't solve your problem, which must be elsewhere.

I'm not sure why you're putting this in the Session, though, as you can read Request.Url.Host directly during the Action.

0
votes

When you create cookie then you must write

Response.AppendCookie("Your cookie name");

And if you want to get that then something like this

if (Request.Cookies["Your cookie name"] != null)
    {
        string value = Request.Cookies["Your cookie name"].Value;
    }

and must if there are different solutions then

machineKey

need to be same which is under

system.web

in web.config and then write

<httpCookies domain=".yourdomainname.com" />