【问题标题】:How can I use session variables in a static method?如何在静态方法中使用会话变量?
【发布时间】:2019-11-12 20:36:07
【问题描述】:

我正在使用 ASP.NET Core。如何在静态方法中使用会话变量?

在 ASP.NET 中,这看起来像这样:

protected static string AssignSession()  
{
    return HttpContext.Current.Session["UserName"].ToString();
}

protected void Page_Load(object sender, EventArgs e)
{
    Session["UserName"] = "super user";
}

当我在 ASP.NET Core 中尝试时,我收到以下错误:

非静态字段、方法需要对象引用, 或属性“ControllerBase.HttpContext”。

【问题讨论】:

  • 先生,我在问 Asp.net-core。
  • 试试System.Web.HttpContext.Current.Session[...]
  • 首先,为什么要使用静态方法?其次,在 ASP.NET Core 中没有静态 HttpContext 实例,也没有 Page_Load 事件 - 根本没有事件。 HttpContext 现在是控制器或 PageModel 的属性。在您也可以使用它之前,您将拥有to enable Session。如果您想以其他方法访问 Session 对象,则必须将其作为参数传递

标签: c# asp.net-core


【解决方案1】:

答案通常是:你不知道。

在 ASP.NET Core 中,您几乎可以避免使用静态代码。相反,ASP.NET Core 使用 dependency injection 使服务作为依赖项可用并控制它们的生命周期。

ASP.NET 中的静态实用程序类可能会转换为 ASP.NET Core 中的单例服务。使用它非常简单;你首先创建一个非静态服务来做你想做的任何事情。由于这是使用依赖注入,因此您也可以只依赖其他服务:

public class MyService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

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

    public void SetSomeSessionValue(string value)
    {
        var httpContext = _httpContextAccessor.HttpContext;

        httpContext.Session["example"] = value;
    }
}

你可以在那里做任何你想做的事。 IHttpContextAccessor 用于检索当前的 HttpContext。

然后,您需要使用依赖注入容器注册您的服务。您可以在 Startup.csConfigureServices 方法中执行此操作:

services.AddSingleton<MyService>();

// we also add the HttpContextAccessor, in case it wasn’t already (implicitly) registered before
services.AddHttpContextAccessor();

现在,您可以在控制器或其他服务中依赖此MyService,只需将其添加为构造函数参数即可:

public class HomeController
{
    private readonly MyService _myService;

    public HomeController(MyService myService)
    {
        _myService = myService;
    }

    public IActionResult Index()
    {
        _myService.SetSomeSessionValue("test");
        return View();
    }
}

现在,您有了一个具有明确依赖关系并且可以正确测试的非静态服务。


话虽如此,许多构造已经可以访问当前的HttpContext 以及会话。例如,在控制器、Razor 页面甚至 Razor 视图中,您可以直接访问 HttpContext,因为它是一个 instance 变量。

因此,如果您不构建一些可重用的实用程序代码,您实际上不需要为此创建服务。例如,您可以在控制器中创建一个(非静态)实用程序方法,然后直接访问 HttpContext

【讨论】:

    猜你喜欢
    • 2011-02-04
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2010-12-06
    相关资源
    最近更新 更多