簡體   English   中英

無法在 asp.net core 中使用 HttpContext.Session

[英]Cannot use HttpContext.Session in asp.net core

我添加了app.UseSession(); 到我的 startup.Configure 和services.AddSession()到我的 ConfigureServices。

現在,如果我嘗試像這樣使用 Session:

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

我得到“非靜態字段、方法或屬性‘HttpContext.Session’需要對象引用”

但是,如果我嘗試像這樣實例化它: HttpContext context = new HttpContext();

它說:“無法創建抽象類或接口‘HttpContext’的實例”

如何訪問會話?

查詢文件

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

在您的類中,將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.AddHttpContextAccessor(); services.AddControllersWithViews();

在這個類的外部,使用它來獲取當前的 HttpContext。

HttpContext context = HttpContext.Current;

然后將其注入到該類的構造函數中。 你一定有這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM