使用 IAppBuilder.UseWebApi 时出现问题

Issue when using IAppBuilder.UseWebApi

我正在 ASP .NET MVC5 中使用 WebApis 创建一个 SPA(单页应用程序)。 对于 WebAPI,我使用的是属性路由。对于 Web API 以外的请求,我配置了一个映射到 Home 控制器和 Index 操作的 Catch-All 路由 这是我的代码

我的 StartUp.cs 文件中有以下配置代码

using System.Web.Routing;

[assembly: OwinStartup(typeof(MyApp.Startup))]

namespace MyApp

{

public class Startup
{

    public void Configuration(IAppBuilder app)
    {

        GlobalConfiguration.Configure(WebApiConfig.Register);
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);            


        //app.UseWebApi(GlobalConfiguration.Configuration); 

    }

}
}

我的WebApiConfig.Register方法如下

public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
}

对于WebApis以外的路由,我注册了以下路由

 public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "CatchAll",
            url: "{*url}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

    }
}

现在在 StartUp class 的 Configuration 方法中,如果我取消注释这一行

        app.UseWebApi(GlobalConfiguration.Configuration)

并尝试访问任何路由,我收到此错误

<Error>
    <Message>
    No HTTP resource was found that matches the request URI 'http://localhost:17212/orders'.
    </Message>
    <MessageDetail>
    No type was found that matches the controller named 'Home'.
    </MessageDetail>
</Error>

为什么会这样?可以保留此行注释吗?

您正在混合配置。 app.UseWebApi 主要用于 OWIN 管道而不是 MVC,因此当您使用该设置时,它会否定您的 MVC 配置,因为它会接管传入请求的检查。如果您混合使用 MVC 和 Web API,您可以安全地对该行进行注释。