【问题标题】:When/Where should i create the following class in my ASP.NET MVC project?我应该何时/在何处在我的 ASP.NET MVC 项目中创建以下类?
【发布时间】:2010-03-02 10:34:44
【问题描述】:

我有一个简单的类,其中包含有关当前网站的一些一般信息:-

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。那是柯尔。但我不确定如何从 url 中提取 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 在抽象控制器中为空。事实上,在抽象控制器中,大部分信息都是空的。

所以我不确定何时读取这些值并创建该类的正确位置。

有人有想法吗?

【问题讨论】:

    标签: c# asp.net-mvc api


    【解决方案1】:

    您可能想尝试在 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

    【讨论】:

    • 是的,这对我来说是个合适的地方。 +1
    • 是的。确认的。不知道你可以这样做。酱汁真棒。
    猜你喜欢
    • 2011-05-20
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 2020-02-03
    相关资源
    最近更新 更多