事實證明,只有兩種方法可以解決將WebAPI 2.2添加到現有項目時出現的配置問題。當我閱讀代碼時,我正在做兩個修補程序,這些修補程序都變得很清楚。
以下:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
class WebApiConfig
{
public static void Register()
{
GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes());
}
}
幾乎是一樣執行以下操作:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//WebApiConfig.Register();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.MapHttpAttributeRoutes();
}
}
看來我只是經歷一個心理時隔:)
這應該是很明顯那GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes())
基本上和GlobalConfiguration.Configure(WebApiConfig.Register)
一樣。
從邏輯上說,它們應該產生相同的結果。以下是System.Web.Http名稱空間中GlobalConfiguration的Microsoft代碼:
/// <summary>
/// Provides a global <see cref="T:System.Web.Http.HttpConfiguration"/> for ASP.NET applications.
/// </summary>
public static class GlobalConfiguration
{
private static Lazy<HttpConfiguration> _configuration = CreateConfiguration();
///... code excluded for brevity
/// <summary>
/// Gets the global <see cref="T:System.Web.Http.HttpConfiguration"/>.
/// </summary>
public static HttpConfiguration Configuration
{
get { return _configuration.Value; }
}
/// <summary>
/// Performs configuration for <see cref="GlobalConfiguration.Configuration"/> and ensures that it is
/// initialized.
/// </summary>
/// <param name="configurationCallback">The callback that will perform the configuration.</param>
public static void Configure(Action<HttpConfiguration> configurationCallback)
{
if (configurationCallback == null)
{
throw new ArgumentNullException("configurationCallback");
}
configurationCallback.Invoke(Configuration);
Configuration.EnsureInitialized();
}
private static Lazy<HttpConfiguration> CreateConfiguration()
{
return new Lazy<HttpConfiguration>(() =>
{
HttpConfiguration config = new HttpConfiguration(new HostedHttpRouteCollection(RouteTable.Routes));
ServicesContainer services = config.Services;
Contract.Assert(services != null);
services.Replace(typeof(IAssembliesResolver), new WebHostAssembliesResolver());
services.Replace(typeof(IHttpControllerTypeResolver), new WebHostHttpControllerTypeResolver());
services.Replace(typeof(IHostBufferPolicySelector), new WebHostBufferPolicySelector());
services.Replace(typeof(IExceptionHandler),
new WebHostExceptionHandler(services.GetExceptionHandler()));
return config;
});
}
///... code excluded for brevity
}