반응형
ASP.NET MVC 글로벌 변수
ASP.NET MVC에서 글로벌 변수를 어떻게 선언합니까?
기술적으로 클래스의 정적 변수 또는 속성은 프로젝트의 모든 위치에서 글로벌 변수가 됩니다.
public static class MyGlobalVariables
{
public static string MyGlobalString { get; set; }
}
그러나 @SLAK가 말하는 것처럼 올바르게 처리하지 않으면 '잠재적으로' 잘못된 관행이 될 수 있고 위험할 수 있습니다.예를 들어, 위의 예에서는 동일한 속성에 액세스하려는 요청(스레드)이 여러 개 있을 수 있습니다. 이 요청은 복잡한 유형이나 컬렉션인 경우 문제가 될 수 있으며 어떤 형태로든 잠금을 구현해야 합니다.
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;
}
}
}
응용프로그램에 저장할 수 있습니다.
Application["GlobalVar"] = 1234;
현재 IIS/가상 응용 프로그램 내에서만 글로벌합니다.즉, 웹 팜에서는 서버에 로컬이며 응용프로그램의 루트인 가상 디렉터리 내에 있습니다.
정적 변수가 아닌 변수의 경우 아래와 같이 Application 클래스 사전을 통해 정렬했습니다.
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
반응형
'programing' 카테고리의 다른 글
| Vuex 변환: ES6 구문을 사용하여 상태 매개변수를 분해합니다(퀘이사 프레임워크 사용). (0) | 2023.06.28 |
|---|---|
| Windows git "경고: LF가 CRLF로 대체됩니다", 이 경고 테일이 역방향입니까? (0) | 2023.06.28 |
| gradle build와 gradle bootJar의 차이점은 무엇입니까? (0) | 2023.06.28 |
| create oracle package funched PLS-00103: 기호 "CREATE"를 발견했습니다. (0) | 2023.06.23 |
| 제이드/퍼그로 인라인 자바스크립트를 렌더링하려면 어떻게 해야 합니까? (0) | 2023.06.23 |