繁体   English   中英

在C#Web应用程序中使用静态变量-在类属性中访问会话变量

[英]Using static variables in C# Web Application - Accessing Session variables in class properties

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

我对这个ASP.Net Web应用程序(核心)不是很陌生,但是我仍然很纳闷。

在当前应用程序中,我有一个类,该类具有一个属性,该属性可从静态变量获取该属性,该静态变量是在用户请求控制器时设置的。 因此流程为:用户发送一个请求,该请求的主体中带有变量,如果未在主体中指定,则将StaticClass.StaticProperty(示例)设置为用户在主体中指定的变量(或默认= 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

变量始终为null。

感谢您的帮助。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM