WebAPI + MVC + Owin:MVC 路由不起作用

WebAPI + MVC + Owin: MVC routes don't work

我有一个带有 OWIN 的 WebAPI 2 应用程序。现在我正在尝试向所有内容添加 MVC 5 控制器,但未找到我的 MVC 路由。我收到以下错误:

No HTTP resource was found that matches the request URI 'https://localhost:44320/home'.

No type was found that matches the controller named 'home'.

控制器名称正确(HomeController),它是public,我在Global.asax中配置路由:

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    ModelBinderConfig.RegisterModelBinders(config.Services);
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

我也有 OWIN Startup class:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = GlobalConfiguration.Configuration;

        var globalExceptionHandler = GetGlobalExceptionHandlerConfiguration();
        config.Services.Replace(typeof(IExceptionHandler), globalExceptionHandler);
        app.UseWebApi(config);
    }
}

我注意到当我注释掉 app.UseWebApi(config) 行时,MVC 路由又开始工作了。

有谁知道这是怎么回事以及如何解决这个问题?

谢谢

尝试将此代码添加到您的 RouteConfig.cs 文件中。

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

app.UseWebApi()命令用于OWIN自托管,与MVC不兼容,所以只能在你的项目完全是一个Web项目时使用Api。只需删除它,您就可以了。

在我的例子中,我不得不将所有配置从 post 中的 Application_Start 移动到 Startup.Configuration 替换 app.UseWebApi(config);

这在 owin 启动中对我有用 class。

// instead of : app.UseWebApi(GlobalConfiguration.Configuration)    
app.UseWebApi(new HttpConfiguration());