【问题标题】:ASP.NET : How to Manage State in Class Library?ASP.NET:如何管理类库中的状态?
【发布时间】:2016-05-04 16:08:35
【问题描述】:

我有一个带有几个类库 (.NET 4.6.1) 的 ASP.NET MVC 6 应用程序。现在我想在 asp.net 应用程序和类库之间传递值。例如,我想从类库中访问 UserId(在会话中)。我不想使用参数来传递值,因为 UserId 是我的类库中的全局变量,并且我没有来自类库中 Web 应用程序的引用。解决这个问题的最佳方法是什么?

  • 在类库中使用会话?
  • 使用共享内存?
  • 使用网络服务?
  • 使用数据库?
  • ... ?

更新: https://stackoverflow.com/a/2040623/2455393 说我们可以使用这个:

using System.Web;
var currentSession = HttpContext.Current.Session;
var myValue = currentSession["myKey"];

在 .NET 4.6.1 (MVC 6) 中它不起作用。但在 .NET 4.0 中它运行良好。这是我的问题。

【问题讨论】:

  • "I don't have a reference from web application in the class library" - 那么应用程序如何首先引用该代码?我不太清楚你想在这里做什么。
  • 在我看来这对 ClaimsIdentity 很有用。
  • 很清楚。类库不依赖于 Web 应用程序。但是 Web 应用程序使用了类库。在 .NET 4.0 中,我使用 HttpContext.Request.Session 来访问两者之间的共享数据。

标签: asp.net session asp.net-core-mvc class-library


【解决方案1】:

我在类库中没有来自 Web 应用程序的引用。 解决这个问题的最佳方法是什么?

理想情况下,类库不应访问 HttpContext (除非它与表示层相关)。相反,您只需将 UserId 作为参数传递给方法。

否则,将很难对类库进行单元测试。

表示层怎么样

如果你想访问控制器内部的 userId,你想注入它,而不是直接从 HttpContext 访问它。

例如,

public interface IUserSession
{
    int Id { get; }
    string FirstName { get; }
    string LastName { get; }
    string UserName { get; }
    bool IsInRole(string roleName);
}

public interface IWebUserSession : IUserSession
{
    Uri RequestUri { get; }
    string HttpRequestMethod { get; }
}

public class UserSession : IWebUserSession
{
    public int Id => Convert.ToInt32(((ClaimsPrincipal) HttpContext.Current.User)?.FindFirst(ClaimTypes.Sid)?.Value);

    public string FirstName => ((ClaimsPrincipal)HttpContext.Current.User)?.FindFirst(ClaimTypes.GivenName)?.Value;

    public string LastName => ((ClaimsPrincipal) HttpContext.Current.User)?.FindFirst(ClaimTypes.Surname)?.Value;

    public string UserName => ((ClaimsPrincipal)HttpContext.Current.User)?.FindFirst(ClaimTypes.Name)?.Value;

    public bool IsInRole(string roleName) => HttpContext.Current.User.IsInRole(roleName);

    public Uri RequestUri => HttpContext.Current.Request.Url;

    public string HttpRequestMethod => HttpContext.Current.Request.HttpMethod;
}

用法

public class MyController : Controller
{
   private readonly IWebUserSession _webUserSession;

   public MyController(IWebUserSession webUserSession)
   {
      _webUserSession = webUserSession;
   }
}

【讨论】:

  • 它在类库中使用 (ClaimsPrincipal) HttpContext.Current.User。问题是类库中的 HttpContext 为空(在 MVC 6 中)
  • 正如我所说,在类库中使用 HttpContext 是错误的。你想把它留在Presentation Layer
  • “正如我所说,在类库中使用 HttpContext 是错误的”那么解决方案是什么?
  • 您只需将 UserId 作为参数传递给类库的方法
  • 没有看到您的代码,我无法推荐您应该做什么。如果你关注SOLID design principle,类库甚至不应该知道你使用的是什么前端。理想情况下,您应该能够从 Web 应用程序切换到 WPF,而无需修改类库中的一行代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 2011-02-08
  • 2020-06-16
  • 1970-01-01
  • 2017-09-02
  • 2020-03-29
相关资源
最近更新 更多