如何在ASP.NET Core中获取HttpContext.Current.Session?

3

我需要将一个MVC项目迁移到.net Core,我知道ASP.net Core已经删除了System.Web。在ASP.net Core中,我需要将HttpContext.Current.Session ["name"]! = Null进行转换。我添加了using Microsoft.AspNetCore.Http,但是出现了错误。


一个简单的谷歌搜索就可以给你这个信息,不过无论如何,在控制器中可以通过request.httpcontext访问它,在视图中可以使用context这个关键词来访问。 - undefined
在控制器中它可以工作,但在服务层级上却无法工作。 - undefined
@user3296338 在启动类中添加了 services.AddSession();app.UseSession(); 吗? - undefined
4个回答

8

使用方法如下:

HttpContext.Session.SetString("priceModel", JsonConvert.SerializeObject(customobject));
var priceDetails = HttpContext.Session.GetString("priceModel");

确保启动类中以下几点:

  1. AddSession in ConfigureServices method

    services.AddSession();
    
  2. Usesession in configure method:

    app.UseSession();
    

3

在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;    
    }

上面的代码通过依赖注入接收IHttpContextAccessor对象,然后将Sessions存储在一个本地变量中。

1
推荐的方法是使用内置的依赖注入容器注册依赖项。将IHttpContextAccessor注入到相应的服务中。
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);
        }
    }

更多细节请参考此链接:this link

0

你测试过微软文档了吗?一个示例如下:

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);

在控制器中它能够正常工作,但在服务层级上却无法运行。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接