WebApiConfig.Register()与GlobalConfiguration.Configure()

ale*_*lex 7 c# asp.net-web-api2

我有一个参考Web API 2的项目,我正在解决一些路由问题.据我所知,正确的方法是确保Global.asax文件中存在以下代码行:

GlobalConfiguration.Configure(WebApiConfig.Register);
Run Code Online (Sandbox Code Playgroud)

但在此过程中,我选择了以下代码:

WebApiConfig.Register(GlobalConfiguration.Configuration);
Run Code Online (Sandbox Code Playgroud)

Global.asax将两行代码都识别为有效.有什么不同?

Nko*_*osi 7

来源:ASP.NET Web API 2中的属性路由

从Web API迁移1

在Web API 2之前,Web API项目模板生成如下代码:

protected void Application_Start()
{
    // WARNING - Not compatible with attribute routing.
    WebApiConfig.Register(GlobalConfiguration.Configuration);
}
Run Code Online (Sandbox Code Playgroud)

如果启用了属性路由,则此代码将引发异常.如果升级现有Web API项目以使用属性路由,请确保将此配置代码更新为以下内容:

protected void Application_Start()
{
    // Pass a delegate to the Configure method.
    GlobalConfiguration.Configure(WebApiConfig.Register);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。我很惊讶 Web API 2 仍然接受 `WebApiConfig.Register(GlobalConfiguration.Configuration);` 而不会抛出错误。 (2认同)