在现有的ASP.NET MVC 5项目中使用WebAPI 2.2

本文关键字:项目 WebAPI MVC ASP NET | 更新日期: 2023-09-27 18:23:47

我在现有的MVC 5项目中使用带有属性路由的WebAPI 2.2。我打算将整个网站迁移到WebAPI,但这需要一些时间。我把一切都安排好了,但我担心我可能做错了什么。

这篇SO文章似乎建议我应该调用Global.asax.cs文件中的GlobalConfiguration.Configure(WebApiConfig.Register)。

如果我简单地删除通常在WebApiConfig.Register()中提供的HttpConfiguration参数,并简单地在WebApiConfig.Register()方法中调用GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes()),那么WebAPI端点将以所需的结果进行响应。

这就是我最终得到的:

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());
    }
}

这种方法有什么问题吗?

在现有的ASP.NET MVC 5项目中使用WebAPI 2.2

因此,有两种方法可以解决将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
}