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

标签 c# asp.net-mvc

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

public string SiteName;

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

   SiteName = currentUrl;         

   return View();

}

最佳答案

由于您使用的是 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();
}

关于c# - 如何在c#方法中设置一个全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49380912/

相关文章:

C#,如何在 RGB 中生成仅与 CMYK 兼容的颜色

c# - UWP:ListView ItemClick 不起作用

C# 何时使用 "This"关键字

c# - 不可能从物体转换到短

asp.net-mvc - ASP.NET MVC TextBoxFor 占位符

Asp.net mvc 在部分网站上运行

c# - C#内存不足异常

c# - ASP MVC 即使未提供任何参数也创建参数模型

android - 将 Android 手机与 ASP.net MVC 4 应用程序连接的 Web 服务

asp.net - 当用户使用 CAS SSO 注销时,ASP.NET MVC 触发 HttpRequestValidationException