首页 > 解决方案 > 在 .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. 是否有不同的方法来创建可以在控制器中引用的变量?

标签: c#asp.net-mvcasp.net-core

解决方案


get我认为,如果您为该字段定义 a ,则可以完成您想要实现的目标:

public int _loggedInUserID { get => int.Parse(HttpContext.User.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value); }

然后你的代码应该编译。


推荐阅读