반응형
ASP.NET MVC 전역 변수
ASP.NET MVC에서 전역 변수를 어떻게 선언합니까?
public static class GlobalVariables
{
// readonly variable
public static string Foo
{
get
{
return "foo";
}
}
// read-write variable
public static string Bar
{
get
{
return HttpContext.Current.Application["Bar"] as string;
}
set
{
HttpContext.Current.Application["Bar"] = value;
}
}
}
기술적으로 프로젝트의 모든 위치에있는 클래스의 모든 정적 변수 또는 속성은 전역 변수가됩니다.
public static class MyGlobalVariables
{
public static string MyGlobalString { get; set; }
}
그러나 @SLaks가 말했듯이 올바르게 취급하지 않으면 '잠재적으로'나쁜 습관이되고 위험 할 수 있습니다. 예를 들어, 위의 예에서 동일한 속성에 액세스하려고하는 여러 요청 (스레드)이있을 수 있습니다. 이는 복잡한 유형이나 컬렉션 인 경우 문제가 될 수 있습니다. 어떤 형태의 잠금을 구현해야합니다.
응용 프로그램에 넣을 수 있습니다.
Application["GlobalVar"] = 1234;
현재 IIS / 가상 응용 프로그램 내에서만 전역 적입니다. 즉, 웹팜에서는 서버에 로컬이며 응용 프로그램의 루트 인 가상 디렉터리 내에 있습니다.
들어 비 정적의 변수, 내가 통해 그것을 정리 응용 프로그램 수준의 사전 다음과 같이 :
Global.asax.ac :
namespace MvcWebApplication
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
private string _licensefile; // the global private variable
internal string LicenseFile // the global controlled variable
{
get
{
if (String.IsNullOrEmpty(_licensefile))
{
string tempMylFile = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(LDLL.License)).Location), "License.l");
if (!File.Exists(tempMylFile))
File.Copy(Server.MapPath("~/Content/license/License.l"),
tempMylFile,
true);
_licensefile = tempMylFile;
}
return _licensefile;
}
}
protected void Application_Start()
{
Application["LicenseFile"] = LicenseFile;// the global variable's bed
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
그리고 컨트롤러에서 :
namespace MvcWebApplication.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View(HttpContext.Application["LicenseFile"] as string);
}
}
}
이런 식으로 ASP.NET MVC에서 전역 변수를 가질 수 있습니다. :)
참고 : 개체가 문자열이 아닌 경우 다음과 같이 작성하십시오.
return View(HttpContext.Application["X"] as yourType);
Config 클래스 또는 그 라인을 따라 무언가와 같은 정적 클래스를 사용할 수도 있습니다.
public static class Config
{
public static readonly string SomeValue = "blah";
}
강철은 뜨겁지 않지만 @abatishchev의 솔루션을 이 게시물 의 답변과 결합 하여이 결과를 얻었습니다. 유용하기를 바랍니다.
public static class GlobalVars
{
private const string GlobalKey = "AllMyVars";
static GlobalVars()
{
Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;
if (table == null)
{
table = new Hashtable();
HttpContext.Current.Application[GlobalKey] = table;
}
}
public static Hashtable Vars
{
get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
}
public static IEnumerable<SomeClass> SomeCollection
{
get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
set { WriteVar("SomeCollection", value); }
}
internal static DateTime SomeDate
{
get { return (DateTime)GetVar("SomeDate"); }
set { WriteVar("SomeDate", value); }
}
private static object GetVar(string varName)
{
if (Vars.ContainsKey(varName))
{
return Vars[varName];
}
return null;
}
private static void WriteVar(string varName, object value)
{
if (value == null)
{
if (Vars.ContainsKey(varName))
{
Vars.Remove(varName);
}
return;
}
if (Vars[varName] == null)
{
Vars.Add(varName, value);
}
else
{
Vars[varName] = value;
}
}
}
참고 URL : https://stackoverflow.com/questions/5118610/asp-net-mvc-global-variables
반응형
'Nice programing' 카테고리의 다른 글
JavaScript로 모든 쿠키를 삭제하려면 어떻게해야합니까? (0) | 2020.10.28 |
---|---|
JavaScript에서 String.Format 사용? (0) | 2020.10.28 |
산란 용 matplotlib 컬러 바 (0) | 2020.10.28 |
편집 텍스트 커서 색상 변경 (0) | 2020.10.28 |
Html Agility Pack은 클래스별로 모든 요소를 가져옵니다. (0) | 2020.10.28 |