[英]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.