我的解决方案中有 2 个项目。
- MVC Web 应用程序
类库
- MVC Web 应用程序引用类库。
- 类库包含一个扩展默认 ASP.Net Controller 的类。
我在应用程序的 Global.asax 中的 session 中放置了一个变量。
protected void Session_Start(object sender, EventArgs args)
{
HttpContext.Current.Session["DomainName"] = Request.Url.Host;
}
在类库中,我尝试从 HttpContext.Session 获取值,但 HttpContext.Session 始终为空。
public class MyController : System.Web.Mvc.Controller
{
public MyController () : base()
{
//HttpContext.Session is always null at this point
ViewData["DomainName"] = HttpContext.Session["DomainName"];
}
}
HttpContext.当前.Session 似乎不是 Controller 中的选项。有什么想法吗?
最佳答案
有两个问题——Controller 类中的 HttpContext 属性是当前 session 。不幸的是,它在 Controller 的构造函数中不可用。显然,因为它没有在构造函数中传递,所以必须在之后通过属性进行设置。您可以考虑添加一个属性来保存域名并从中引用 session ——这样就可以在需要时使用。
protected string DomainName
{
get { return this.HttpContext.Session["DomainName"] as string; }
}
在操作中的 ViewData 或 OnActionExecuting/OnActionExecuted 中设置它。
protected override void OnActionExecuted( ActionExecutedContext context )
{
ViewData["DomainName"] = this.HttpContext.Session["DomainName"];
// or ViewData["DomainName"] = this.DomainName; // if you used the property
}
关于ASP.NET MVC : How do you access the session from a different project within the solution?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2200875/