public 字段对于控制器中的某些用户是否具有不同的值?

Is public field has different values for some users in controller?

我有三个操作方法和 public 字段 public int idUser:

public class HomeController : Controller
{   
    //public field 
    public int idUser = 0; 

    public ActionResult Index()
    {   
        string userLogin = User.Identity.Name;                        
        using (SmoothEntities db = new SmoothEntities())
        {                
            idUser = (db.Users.Where(c => c.Name == userLogin).First()).ID_User;
            return View(db.Employees.Where(u => u.ID_User == idUser).ToList());
        }  
    }
    public ActionResult About()
    {
        string userLogin = User.Identity.Name;            
        int idUser = 0;
        using (SmoothEntities db = new SmoothEntities())
        {                
            idUser = (db.Users.Where(c => c.Name == userLogin).First()).ID_User;
            return View(db.Employees.Where(u => u.ID_User == idUser).ToList());
        }  
    }

    public ActionResult Contact()
    {            
        return View();
    }
}

假设 Bob 和 Bill 同时登录到该网站。如果 Bob 将执行 public ActionResult Index() 并且 Bill 将执行 public ActionResult About()?

为什么要使用 public 字段?因为我不想总是在 Action 方法中从服务器访问数据,我认为这会降低我网站的性能,所以我决定创建 public 字段。

Am I right that Bob and Bill will have two different values of the public field idUser if Bob will execute public ActionResult Index() and Bill will execute public ActionResult About()?

是的,你是对的(即使他们执行相同的方法)。

默认情况下,对于命中 asp.net mvc 的每个请求,asp.net mvc 将创建控制器的 新实例 来为请求提供服务这样他们就不会共享字段值。

不管它是不是一个好主意,是的,每个请求都会有一个不同的控制器实例class,所以这个领域也是如此。您可以通过实现控制器构建器来覆盖此行为,该构建器以某种方式缓存和 returns 相同的控制器实例到 all/some 请求。如果您只想共享您的字段,请将其设为静态。