c# - 在 .Net Core 中,如何在 HttpContext 的控制器中设置变量以在所有控制器方法中使用?
问题描述
我想设置一个可以被控制器中的其他方法访问的变量。
public class ReportsController : Controller
{
public readonly int loggedInUserID = int.Parse(HttpContext.User.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value);
public IActionResult Index()
{
/*I would like to be able to access this variable in many controller methods
without having to copy 'int.Parse(HttpContext.User.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value)'
for each reference.*/
int userID = loggedInUserID;
return View();
}
}
当我尝试创建 loggedInUserID 变量时,错误消息指出:A field initializer cannot reference the non-static field, method, or property 'ControllerBase.HttpContext.
是否有不同的方法来创建可以在控制器中引用的变量?
解决方案
get
我认为,如果您为该字段定义 a ,则可以完成您想要实现的目标:
public int _loggedInUserID { get => int.Parse(HttpContext.User.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value); }
然后你的代码应该编译。
推荐阅读
- python - setup.py 构建后无法导入模块
- php - 如何使用折叠/展开选项制作 jQuery 数据表 mysql php
- python - 使用 Python 进行参数曲线拟合
- python - Python数据框部分字符串替换
- reactjs - 即使响应为 200,S3 React Typescript 也不会上传文件
- node.js - 如何在 MERN 应用中实现登录功能?
- vba - 如何使用用于格式化表格的宏计算选择中有多少个选项卡
- php - PHP比较字符串日期值正在输出不同的输出
- java - 是否可以通过使用 Google Map API 知道特定街道是否是一种方式?
- domain-driven-design - 为什么存储库与域实体一起使用?