Problem with a static variable

I have a problem with a static variable. Part of the organization of my controllers is as follows:

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);
        }
     }
}

The problem arises when several users use this view at the same time. The same static variable is used by all users and changes its value. How to solve this?

+3
source share
6 answers

you can use

HttpContext.Current.Session["some_var"]

instead of some_var, this will help. This will be saved for the user who is registered, one session, and you can get it statically using 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"]); 
        } 
     } 
} 
+7
source

Your application ASP.NET MVC AppDomain, , , !

, AppDomain, .

( "" ) , . , / . ASP.NET , , . , , , .

, , . , -, , . , , .

, , , , , , - .


( ), - . , . , ( OO) , , . , .

+8

, .

( ), :

if (Session["Count"] == null)
    Session["Count"] = 0;
Session["Count"] = (int)Session["Count"] + MyNewValue;

, , .

+6

( ) - - . .

, , , .

, , .

+1

. , , , , , . ( ), .

, , . , . , .

, .

+1

, . . , . country_code, . escape . , , - . , , , , country_code , . , , . , . , . , , , , , , . , county_code_id, , , , , country_code_id country_code , country_code .

As I said, statics are neither good nor bad, they just have a different use.

0
source

Source: https://habr.com/ru/post/1761316/


All Articles