微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 静态变量的问题

我有静态变量的问题.我的控制器组织的一部分如下:

namespace MyApp.Controllers
{
    public class DevicesController : Controller
    {            
        static int some_var = 0;           

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SetValue(int temp){
           some_var = temp;
           return RedirectToAction("displayValue");
        }

        [Authorize]
        public ActionResult displayValue(){              
          .... 
          return View(some_object);
        }
     }
}

当多个用户同时使用此视图时会出现问题.所有用户都使用相同的静态变量并更改其值.怎么解决这个?

解决方法

您可以使用,

HttpContext.Current.Session["some_var"]

而不是some_var,这将有所帮助.这将为记录的用户保留一个会话,您可以使用HttpContext.Current静态访问它

namespace MyApp.Controllers 
{ 
    public class DevicesController : Controller 
    { 

        [AcceptVerbs(HttpVerbs.Post)] 
        public ActionResult SetValue(int temp){ 
           HttpContext.Current.Session["some_var"] = temp; 
           return RedirectToAction("displayValue"); 
        } 

        [Authorize] 
        public ActionResult displayValue(){ 

          ....  
          return View((int)HttpContext.Current.Session["some_var"]); 
        } 
     } 
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐