我有一个带有几个类库(.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中,它运行良好。这是我的问题。
答案 0 :(得分: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;
}
}