【问题标题】:Enable web api attribute routing in global.asax在 global.asax 中启用 web api 属性路由
【发布时间】:2014-12-03 14:56:45
【问题描述】:

我想为 Web API 启用属性路由,因为它看起来会使路由更容易定义。此处的示例:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 显示了它是如何在 WebApiConfig.cs 文件中完成的:

using System.Web.Http;

namespace WebApplication
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            // Other Web API configuration not shown.
        }
    }
}

但是,我的项目是一个旧的 Web 表单项目,最初是在 .Net 2.0 中开始的(经过多年的多次升级,现在是 4.5)。我没有 WebApiConfig.cs 文件,而是直接在 global.asax Application_Start 方法中定义我当前的路由:

RouteTable.Routes.MapHttpRoute(...)

谁能解释在这种情况下启用基于属性的路由的最佳方法? 谢谢

【问题讨论】:

  • 阅读您在“注意:从 Web API 1 迁移”下发布的链接
  • @rhumborl 感谢您的建议。有趣的是,我在 global.asax 中没有提到 WebApiConfig.Register(GlobalConfiguration.Configuration); 的那一行
  • 哇,投反对票?这是一个坏问题吗?谁能告诉我为什么?

标签: c# asp.net asp.net-web-api


【解决方案1】:

你可以在你的Global.asax文件中做GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

GlobalConfiguration.Configuration 对象被传递给WebApiConfig 文件,所以你可以使用这个类在Global.asax 中配置所有你需要的东西

【讨论】:

    【解决方案2】:

    你应该把这两行放在你的路由定义之前,它会很好地工作

      GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
      GlobalConfiguration.Configuration.EnsureInitialized();
    

    干杯

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 2017-08-16
      • 2015-03-29
      相关资源
      最近更新 更多