我需要将一个MVC项目迁移到.net Core,我知道ASP.net Core已经删除了System.Web。在ASP.net Core中,我需要将HttpContext.Current.Session ["name"]! = Null进行转换。我添加了using Microsoft.AspNetCore.Http,但是出现了错误。
我需要将一个MVC项目迁移到.net Core,我知道ASP.net Core已经删除了System.Web。在ASP.net Core中,我需要将HttpContext.Current.Session ["name"]! = Null进行转换。我添加了using Microsoft.AspNetCore.Http,但是出现了错误。
使用方法如下:
HttpContext.Session.SetString("priceModel", JsonConvert.SerializeObject(customobject));
var priceDetails = HttpContext.Session.GetString("priceModel");
确保启动类中以下几点:
AddSession in ConfigureServices method
services.AddSession();
Usesession in configure method:
app.UseSession();
在ASP.NET Core中,您没有System.Web.HttpContext.Current.Session。要在非控制器类中访问会话,请执行以下步骤:
第1步:在Startup.ConfigureServices中注册以下服务;
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
步骤2:注册一个类(例如 - TestOrder),在你想要访问Session的地方
Startup.ConfigureServices;
services.AddScoped<TestOrder>();
现在,在TestOrder类中添加以下代码。
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ISession _session;
public TestOrder(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
_session = _httpContextAccessor.HttpContext.Session;
}
public class UserRepository : IUserRepository
{
private readonly IHttpContextAccessor _httpContextAccessor;
public UserRepository(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void LogCurrentUser()
{
var username = _httpContextAccessor.HttpContext.Session.GetString("UserName");
service.LogAccessRequest(username);
}
}
你测试过微软文档了吗?一个示例如下:
public const string SessionKeyName = "_Name";
public const string SessionKeyAge = "_Age";
const string SessionKeyTime = "_Time";
// Requires: using Microsoft.AspNetCore.Http;
if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))
{
HttpContext.Session.SetString(SessionKeyName, "The Doctor");
HttpContext.Session.SetInt32(SessionKeyAge, 773);
}
var name = HttpContext.Session.GetString(SessionKeyName);
var age = HttpContext.Session.GetInt32(SessionKeyAge);
request.httpcontext
访问它,在视图中可以使用context
这个关键词来访问。 - undefined