c# - 在 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
变量始终为空。
感谢您尝试提供帮助。
解决方案
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);
}
}
推荐阅读
- python - 无法使用 xpath 获取标签的内容
- python - 是否可以停止来自 python 程序的所有网络流量?
- python - 仅在开发和生产中执行的 Django 代码
- apache-flink - Apache Flink:如何访问 ReduceFunction 中的广播变量?
- amazon-web-services - 使用 SQL 的 Amazon Kinesis Analytics 中的地理空间函数
- php - 将openssl签名传递给php脚本
- ios - UICollectionViewCell 滚动时显示空白单元格
- javascript - 如何以及何时使用“ng build”生成的 lib 文件夹的 esm5 和 esm2015 目录?
- angular - 如何强制 CSS 文件成为角度项目中呈现的最后一个文件?
- c++ - 到达顶部后将正方形放在左侧