2010-03-02 66 views
2

我有一個包含有關當前網站的一般信息的簡單類: -何時/我應該在ASP.NET MVC項目中創建以下類?

public class WebSiteSettings 
{ 
    public EnvironmentType Environment { get; set } // Eg. Production 
    public VersionType Version { get; set; } // Eg. Version2 
    public string ApiKey { get; set; } // Eg. ABCDE-1234 
} 

現在,我想有以下路線: -

// Api - Search methods. 
routes.MapRoute(
    "Search Methods", 
    "{versionDate}/{controller}/{action}" 
); 

,這裏是一個樣本網址:

http://localhost.api.mydomain.com:1234/2010-01-23/search/posts?user=JonSkeet&apikey=ABCDE-1234

我目前通過自定義ActionFilter來處理檢索apikey。這是關鍵。但我不知道如何從網址中提取versiondate(即2010-01-23)並填充我製作的簡單課程......哪些所有控制器都可以訪問。

我最初想這樣做的:

public abstract class AbstractController : Controller 
{ 
    protected WebSiteSettings WebSiteSettings { get; set; } 

    protected AbstractController() : base() 
    { 
     WebSiteSettings = new WebSiteSettings(); 
     // 1. Read in the version data and figure out the version number. 
     // 2. Read in the app settings to figure out the environment. (easy to do). 
     // 3. No api key just yet. this will be handled in the OnAuthorization action filter. 
    } 
} 

public class SearchController : AbstractController 
{ 
    public ActionResult Posts(..) 
    { // ... blah ... } 
} 

所以,我想這和的RouteData爲空,在抽象控制器。事實上,抽象控制器中的大部分信息都是空的。

所以我不知道什麼時候適當的地方是閱讀這些值並創建該類。

任何人有想法?

回答

2

您可能想嘗試在AbstractController.OnActionExecuting方法中執行此操作,構造函數爲時尚早。

protected override void OnActionExecuting(ActionExecutingContext context) 
{ 
    // context has all the goods 
} 

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting.aspx?ppud=4

+0

是的,這看起來像一個合適的位置給我。 +1 – Odd 2010-03-02 03:40:30

+0

是的。證實。不知道你可以做dat。真棒醬。 – 2010-03-02 03:52:44

相關問題