【问题标题】:Cannot use HttpContext.Session in asp.net core无法在 asp.net 核心中使用 HttpContext.Session
【发布时间】:2020-06-05 19:12:37
【问题描述】:

我已将app.UseSession(); 添加到我的startup.Configure 并将services.AddSession() 添加到我的ConfigureServices。

现在,如果我尝试像这样使用 Session:

HttpContext.Session.SetString("Type", tableName);

我得到“非静态字段、方法或属性‘HttpContext.Session’需要对象引用”

但是,如果我尝试像这样实例化它: HttpContext context = new HttpContext();

它说:“无法创建抽象类或接口'HttpContext”的实例

如何访问会话?

IQuery.cs

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace AppName.Services
{
    public interface IQuery
    {
        List<Dictionary<string, string>> GetListOfDatabases(string dbName);
    }
    public class InMemoryIquery : IQuery
    {
        public List<Dictionary<string, string>> GetListOfDatabases(string tableName)
        {
        if(tableName != null)
            {
               HttpContext.Session.SetString("Type", tableName);
            }
        }
    }

【问题讨论】:

  • 您在什么情况下访问它?见Access HttpContext in ASP.NET Core
  • 我正在尝试从继承接口的类中访问它
  • 你能把完整的代码贴在你试图访问会话的地方吗?
  • 如果您发送访问会话的类的完整代码,我们可以提供帮助。
  • 我已经发布了上面的代码。谢谢

标签: c# asp.net session asp.net-core httpcontext


【解决方案1】:

在你的类中添加 IHttpContextAccessor 到你的构造函数并像这样使用

public class InMemoryIquery : IQuery
{
    private IHttpContextAccessor _httpContextAccessor;

    public InMemoryIquerty(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public List<Dictionary<string, string>> GetListOfDatabases(string tableName)
    {
    if(tableName != null)
        {
           _httpContextAccessor.HttpContext.Session.SetString("CalculationType", tableName);
        }
    }
}

在您的 ConfigureServices 中,在 services.AddControllersWithViews(); 之后添加以下行 services.AddHttpContextAccessor();

【讨论】:

    【解决方案2】:

    在这个类的外面,用这个来获取当前的HttpContext。

    HttpContext context = HttpContext.Current;
    

    然后将其注入到这个类的构造函数中。你必须有这样的东西:

    public InMemoryIquery(HttpContext httpContext)
    {
       httpContext.Session.SetString("CalculationType", tableName);
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-07
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    相关资源
    最近更新 更多