2014-09-19 42 views
0

我在使用應用程序對象時遇到問題。我來自傳統的ASP,所以我知道如何使用它,global.asa等,所以有人可以向我解釋如何在MVC中使用它?使用應用程序對象

在我的Global.asax它看起來像這樣:

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 

     Application.Add("Version", 1); // I want to add this 
    } 
} 

那麼我該如何訪問我的代碼?

我在這兩個控制器和視圖試過這樣:

using System.Web; 

int Version = Application["Version"]; 

,並得到兩個編譯錯誤:

名稱「應用」不在當前情況下存在

有人可以幫我嗎?

+0

你是否得到了一個演員錯誤?嘗試:'int Version =(int)Application [「Version」];' – 2014-09-19 01:01:23

+0

我發佈了錯誤。 – 2014-09-19 01:04:33

+0

那麼....代碼在哪裏?如果您將該代碼放入控制器操作方法中,它應該與演員一起工作。但是,如果你真的像你這樣做了,是的,這將是有問題的,因爲Application是HttpContext的屬性,並且您需要獲取當前上下文來檢查集合。 – 2014-09-19 16:05:04

回答

-1

嘗試訪問這樣說:

HttpContext.Current.Application["Version"] = 1; 
+0

訪問或定義? – 2014-09-19 01:17:48

+0

你應該可以從代碼中推斷出來。 :) – 2014-09-19 01:24:00

+0

是的,你說的訪問,它看起來像你在代碼中定義它,所以我很困惑。但看起來像它的工作原理,但我必須這樣做'string Version = HttpContext.Current.Application [「Version」]。ToString()',它爲什麼不保持它是相同的數據類型? – 2014-09-19 01:27:54

-1

試試這個在您的控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     int Version = (int)HttpContext.Application["Version"]; 
     return View(); 
    } 
} 

與全球:

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
    BundleConfig.RegisterBundles(BundleTable.Bundles); 

    Application.Add("Version", 1); // I want to add this 
} 

我認爲,你只能從動作得到的HttpContext和意見