ASP.NET MVC : How do you access the session from a different project within the solution?

标签 asp.net asp.net-mvc session session-variables

我的解决方案中有 2 个项目。

  1. MVC Web 应用程序
  2. 类库

    • 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/

相关文章:

asp.net - ServiceStack:如何忽略路由?

c# - 本地主机永远等待 ASP.NET 5 应用程序模板项目

ajax 获取后 Php 变量将无法工作

javascript - C# Web 方法未在 javascript 中调用

c# - ASP.NET MVC 路由不工作

c# - Windows Phone - 应用程序级 DispatcherTimer

javascript - 服务器渲染 React js 代码的身份验证 session 技术?

c# - 为什么 Ok() 方法返回 text/plain 媒体类型而不是 application/json?

c# - 如何获取网页内容并将其保存到字符串变量中

asp.net - asp.net webmethod 是否总是返回 jsonified 数据?