如何在c#方法中设置全局变量

时间:2018-03-20 09:48:24

标签: c# asp.net-mvc

我尝试将currenturl分配给SiteName(全局变量),但在更改为新方法时,SiteName(全局变量)变为null。 有人可以帮忙吗?

public string SiteName;

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

   SiteName = currentUrl;         

   return View();

}

3 个答案:

答案 0 :(得分:5)

由于您使用的是asp:为此目的有一个SessionApplication对象:

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

您可以在可以访问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();
}

答案 1 :(得分:5)

在asp.net中使用全局变量MVC不是最佳实践。

我建议改用Session变量。

public ActionResult MyPage(PageData pageData)
{
   Session["SiteName"] = HttpContext.Request.Url.Segments.Last();
   return View();
}

你可以在另一个ActionResult中调用它

public ActionResult MyPage2(PageData pageData)
{
   var SiteName = Session["SiteName"].ToString();
   return View();
}

答案 2 :(得分:4)

我认为您不能定义全局变量,但您可以拥有静态成员

public static class MyStaticValues
{
   public static string currentUrl{get;set;}
}

然后您可以从代码中的任何位置检索它:

String SiteName = MyStaticValues.currentUrl + value.ToString();