从控制器访问时,我MvcApplication的属性为null [英] Property of my MvcApplication is null when accessing it from a controller

查看:146
本文介绍了从控制器访问时,我MvcApplication的属性为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的ASP.NET MVC所以我有这个一个小麻烦。当应用程序启动,我设置一个属性,以一定的价值。然而,当我尝试在一个控制器来访问该属性(使用<一个href=\"http://stackoverflow.com/questions/1066350/how-to-get-mvcapplication-instance-in-asp-net-controller\">this),该属性始终为空。

有什么事情我误解?

在这里,code的简化版本:

 公共类MvcApplication:System.Web.HttpApplication
{
    内部ExtensionManager扩展{搞定;私人集; }    保护无效的Application_Start()
    {
        this.Extensions =新ExtensionManager();
    }
}公众的ActionResult ListExtension()
{
    VAR应用= HttpContext.ApplicationInstance为MvcApplication;
    返回查看(app.Extensions.InstalledExtensions);
}


解决方案

有多个的HttpApplication 整个应用生命周期,但的Application_Start 只调用应用程序第一次初始化时一次。

有关更多信息,请参阅本:<一href=\"http://msdn.microsoft.com/en-us/library/ms178473%28VS.80%29.aspx\">http://msdn.microsoft.com/en-us/library/ms178473%28VS.80%29.aspx

我不知道你是想在这里存储(扩展?)什么,但如果全球所有的用户,那么你可以使用一个静态属性,否则它保存在别处。

I'm relatively new to ASP.NET MVC so I'm having a little trouble with this one. When the application start, I set a property to a certain value. Yet when I try to access this property in a controller (using this), the property is always null.

Is it something I am misunderstanding?

Here a simplified version of the code :

public class MvcApplication : System.Web.HttpApplication
{
    internal ExtensionManager Extensions { get; private set; }

    protected void Application_Start()
    {
        this.Extensions = new ExtensionManager();
    }
}

public ActionResult ListExtension()
{
    var app = HttpContext.ApplicationInstance as MvcApplication;
    return View(app.Extensions.InstalledExtensions);
}

解决方案

There are multiple HttpApplication instances created throughout the application lifecycle but Application_Start is only called once when the application first initialises.

See this for more info: http://msdn.microsoft.com/en-us/library/ms178473%28VS.80%29.aspx

I don't know what you are trying to store here (extensions?) but if its global to all users then you could use a static property, otherwise store it somewhere else.

这篇关于从控制器访问时,我MvcApplication的属性为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆