How do you access application variables in asp.net

2019-01-22 18:15发布

问题:

I set a Application variable in my global.asa.cs with:

    protected void Application_Start()
    {
        ...

        // load all application settings
        Application["LICENSE_NAME"] = "asdf";

    }

and then try to access with my razor view like this:

@Application["LICENSE_NAME"]

and get this error:

Compiler Error Message: CS0103: The name 'Application' does not exist in the current context

what is the proper syntax?

回答1:

Views are not supposed to pull data from somewhere. They are supposed to use data that was passed to them in form of a view model from the controller action. So if you need to use such data in a view the proper way to do it is to define a view model:

public class MyViewModel
{
    public string LicenseName { get; set; }
}

have your controller action populate it from wherever it needs to populate it (for better separation of concerns you might use a repository):

public ActionResult Index()
{
    var model = new MyViewModel
    {
        LicenseName = HttpContext.Application["LICENSE_NAME"] as string
    };
    return View(model);
}

and finally have your strongly typed view display this information to the user:

<div>@Model.LicenseName</div>

That's the correct MVC pattern and that's how it should be done.

Avoid views that pull data like pest, because today it's Application state, tomorrow it's a foreach loop, next week it's a LINQ query and in no time you end up writing SQL queries in your views.



回答2:

@HttpContext.Current.Application["someindex"]


回答3:

You can get the current Application using the automatically generated ApplicationInstance property:

@ApplicationInstance.Application["LICENSE_NAME"]

However, this logic does not belong in the view.



回答4:

You should be able to access this via HttpContext.Current.Application[], however MVC best practices would state that you should probably consider passing this through your View Model.



回答5:

Building on @Darin-Dimitrov pattern answered above, I passed a model into a partial view, which I loaded into a _Layout page.

I needed to load a web page from an external resource on Application Load, which will be used as the header navigation across multiple sites. This is in my Global.asax.cs

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    Application["HeaderNav"] = GetHtmlPage("https://site.com/HeaderNav.html");
}

static string GetHtmlPage(string strURL)
{
    string strResult;
    var objRequest = HttpWebRequest.Create(strURL);
    var objResponse = objRequest.GetResponse();
    using (var sr = new StreamReader(objResponse.GetResponseStream()))
    {
        strResult = sr.ReadToEnd();
        sr.Close();
    }
    return strResult;
}

Here is my controller Action for the partial view.

public class ProfileController : BaseController
{
    public ActionResult HeaderNav()
    {
        var model = new Models.HeaderModel
        {
            NavigationHtml = HttpContext.Application["HeaderNav"] as string
        };
        return PartialView("_Header", model);
    }
}

I loaded the partial view in the _Layout page like this.

<div id="header">
     @{Html.RenderAction("HeaderNav", "Profile");}
</div>

The partial view _Header.cshtml is very simple and just loads the html from the application variable.

@model Models.HeaderModel
@MvcHtmlString.Create(Model.NavigationHtml)


回答6:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        var e = "Hello";
        Application["value"] = e;
    }

@HttpContext.Current.Application["value"]