[英]Referencing ASP.NET framework 4.6.2 in ASP.NET Core, Which use System.Web.HttpContext.Current
我在ASP.Net Framework 4.6 SessionHelper中有一个类,该类的代码如下
using System;
using System.Web;
using MyPortal.Common.Entity;
using MyPortal.Common.Helper;
namespace MyPortal.BusinessLayer.Helper
{
public static class SessionHelper
{
public static User GetLoggedInUser { get { return (User) GetFromSession(User.SESSION_LOGGEDIN_USER); } }
public static User GetLoggedInExternalUser { get { return (User)GetFromSession(User.SESSION_LOGGEDIN_EXTERNAL_USER); } }
public static string GetValueFromSession(string sessionKey)
{
return HttpContext.Current.Session[sessionKey] == null ? string.Empty : HttpContext.Current.Session[sessionKey].ToString();
}
public static void SaveInSession(string sessionKey, object sessionValue)
{
HttpContext.Current.Session[sessionKey] = sessionValue;
}
public static void RemoveSession(string sessionKey)
{
if (HttpContext.Current.Session[sessionKey]!=null)
HttpContext.Current.Session.Remove(sessionKey);
}
}
}
现在,此SessionHelper类可在MyPortal.BusinessLayer的许多地方使用,该项目或dll在ASP.NET Web项目中运行良好。
现在,我必须在ASP.NET Core项目中使用此BusinessLayer.dll,并想访问某些方法,例如获取loginInUserBalance,在BusinessLayer.dll中,这些方法都使用SessionHelper,而SessionHelper本身使用HttpContext.Current.Session
现在我在ASP.NET Core中遇到错误
System.TypeLoadException HResult = 0x80131522消息=无法从程序集'System.Web,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a'中加载类型'System.Web.HttpContext'。
理想的方法是使用IHttpContextAccessor。
在启动时,您可以编写如下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddHttpContextAccessor();
services.AddTransient<IUserRepository, UserRepository>();
}
然后,无论您想使用HttpContext到哪里,都可以注入IHttpContextAccesor,如下例所示:
public class UserRepository : IUserRepository
{
private readonly IHttpContextAccessor _httpContextAccessor;
public UserRepository(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void LogCurrentUser()
{
var username = _httpContextAccessor.HttpContext.User.Identity.Name;
service.LogAccessRequest(username);
}
}
本文档文章介绍了有关从各个位置访问httpcontext的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.