首页 > 解决方案 > 在 C# Web 应用程序中使用静态变量 - 在类属性中访问 Session 变量

问题描述

请原谅我缺乏编码知识以及提出正确问题的能力。

我对这个 ASP.Net Web 应用程序(核心)相当陌生,但我仍然想知道..

在我当前的应用程序中,我有一个类,它有一个属性,它从静态变量中获取它,当用户请求控制器时设置。所以流程是:用户发送请求,body中带有变量,如果body中没有指定,则将StaticClass.StaticProperty(示例)设置为用户在body中指定的变量(或默认= 0),返回数据基于变量。然而我想知道,由于这个变量没有线程保证,当 Web 应用程序一次收到 50,000 个请求时,是否可以更改或弄乱它?

我查看了会话并尝试了以下操作:

service.AddSession(); //Not sure this even does anything?
HttpContext.Session.SetString //Setting this works in the controller, but I cant access it elsewhere by GetString
System.Web.HttpContext.Current.Session["test"] // Cant even access System.Web.Httpcontext, doesn't seem to exist.
HttpContext.Current //doesn't exist either
Session["test"] //doesn't exist either

我可以在某个地方发送会话吗?我很迷茫。

不确定这是否有意义,如果需要,我会尝试详细说明。

先感谢您。

编辑:更新信息。

我已将此添加到我的 startup.cs:services.AddSingleton();

        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
        });

        app.UseSession();

设置会话变量: https ://i.imgur.com/CY8rcdk.png

使用会话变量: https ://i.imgur.com/SuLJKzV.png

变量始终为空。

感谢您尝试提供帮助。

标签: c#asp.netsessionstatic

解决方案


HttpContext 只能从特定于请求的事物中访问,因为它是一个且唯一的请求的上下文。框架为每个请求创建新的控制器实例,并注入 HttpContext。如果需要,开发人员的工作是进一步传递它。

我建议阅读这篇关于它的文章:https ://dotnetcoretutorials.com/2017/01/05/accessing-httpcontext-asp-net-core/

首先在您的 startup.cs 中,您需要将 IHttpContextAccessor 注册为如下服务:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

当您创建一个帮助程序/服务类时,您可以注入 IHttpContextAccessor 并使用它。它看起来与此不太相似:

public class UserService : IUserService
{
  private readonly IHttpContextAccessor _httpContextAccessor;

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

  public bool IsUserLoggedIn()
  {
    var context = _httpContextAccessor.HttpContext;
    return context.User.Identities.Any(x => x.IsAuthenticated);
  }
}

推荐阅读