ASP.NET MVC variables globales

Comment déclarer les variables globales dans ASP.NET MVC?

65
demandé sur abatishchev 2011-02-25 17:50:32

6 réponses

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;
        }
    }
}
43
répondu abatishchev 2011-02-25 15:03:01

techniquement, toute variable statique ou propriété sur une classe, n'importe où dans votre projet, sera une variable globale par exemple

public static class MyGlobalVariables
{
    public static string MyGlobalString { get; set; }
}

mais comme le dit @SLaks, ils peuvent être "potentiellement" une mauvaise pratique et dangereux, s'ils ne sont pas manipulés correctement. Par exemple, dans l'exemple ci-dessus, vous auriez plusieurs requêtes (threads) essayant d'accéder à la même Propriété, ce qui pourrait être un problème si c'était un type complexe ou une collection, vous auriez à mettre en œuvre une certaine forme de verrouillage.

76
répondu Sunday Ironfoot 2011-02-25 15:35:35

vous pouvez les mettre dans l'Application:

Application["GlobalVar"] = 1234;

ils ne sont globaux que dans L'application actuelle IIS / Virtual. Cela signifie que, sur un webfarm ils sont locaux au serveur, et dans le répertoire virtuel qui est la racine de l'application.

24
répondu GvS 2011-02-25 14:57:47

Pour non-statique , les variables, j'ai trié via classe d'Application dictionnaire comme ci-dessous:

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

et dans le contrôleur:

namespace MvcWebApplication.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View(HttpContext.Application["LicenseFile"] as string);
        }

    }
}

de cette façon, nous pouvons avoir des variables globales en ASP.NET MVC:)

NOTE: Si votre objet n'est pas string, écrivez simplement:

return View(HttpContext.Application["X"] as yourType);
18
répondu Yasser Zamani 2012-05-21 08:27:04

vous pouvez également utiliser une classe statique, comme une classe de configuration ou quelque chose comme ça...

public static class Config
{
    public static readonly string SomeValue = "blah";
}
8
répondu Ian P 2011-02-25 14:53:10

l'acier est loin d'être chaud, mais j'ai combiné la solution de @abatishchev avec la réponse de ce post et obtenu ce résultat. J'espère que c'est utile:

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;
        }
    }
}
0
répondu paulo.vin 2017-11-13 15:27:04