Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a global variable inside c# method

Tags:

c#

asp.net-mvc

I tried to assign currenturl to SiteName(Global variable) but while changing to a new method SiteName(global variable) getting null. can anyone please help?

public string SiteName;

public ActionResult Admin()
{
   string currentUrl = HttpContext.Request.Url.Segments.Last();

   SiteName = currentUrl;         

   return View();

}
like image 816
Udaya Avatar asked Dec 08 '22 15:12

Udaya


1 Answers

Since you are using asp: there is a Session and Application object for this purpose:

public ActionResult Admin()
{
   string currentUrl = HttpContext.Request.Url.Segments.Last();

   //per session (let's say: per user)
   //you can read and write to this variable
   Session["SiteName"] = currentUrl;   

   //"global" variables: for all users
   HttpContext.Application["SiteName"] = currentUrl;

   return View();
}

You can retrieve it the same way throughout your application where you have access to the httpcontext.

public ActionResult Foo()
{
   //per session (let's say: per user)
   //you can read and write to this variable
   var currentUrl = Session["SiteName"];   

   //or

   //"global" variables: for all users
   currentUrl = HttpContext.Application["SiteName"];

   return View();
}
like image 63
Stefan Avatar answered Dec 18 '22 04:12

Stefan