MVC 5、Web API 和 Owin

MVC 5, Web API And Owin

我说的对吗,Web API 可以在 OWIN 上 运行 而 MVC 5 不能?

所以在我的项目中我仍然需要我的 Global.asax 和 public class WebApiApplication : System.Web.HttpApplication

目前我的 owin Startup.cs 看起来像这样:

public void Configuration(IAppBuilder app)
{
    var httpConfig = new HttpConfiguration
    {

    };


    WebApiConfig.Register(httpConfig);

    app.UseWebApi(httpConfig);
    app.UseCors(CorsOptions.AllowAll);

    RouteConfig.RegisterRoutes(RouteTable.Routes);//MVC Routing
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

RouteConfig.RegisterRoutes(RouteTable.Routes)够了吗?

每当我浏览到任何 MVC 路由时,我都会收到 404。

是的,您是对的,MVC 5(基于 ASP.NET 4)需要 IIS,它不能自托管。 MVC 6(基于 ASP.NET 5,现在称为 ASP.NET Core 1)没有此限制。如果您需要自托管,请开始使用 ASP.NET Core 1(它非常棒),或者如果您现在需要 RTM,请使用 WebAPI。

Am I correct when I say, Web API can run on OWIN and MVC 5 cannot?

不清楚你在问什么,但 OWIN 不是服务器,而是一个中间件,有助于注入管道以便分阶段预处理请求,它不依赖于 WebAPI 或 MVC 版本,但它取决于是否托管服务器实现了 OWIN 规范。

Is RouteConfig.RegisterRoutes(RouteTable.Routes) enough?

是的,这将适用于 Asp.net MVC,但对于 Web api 您需要在单独的配置 class 中注册路由。通常,WebAPI 配置可能看起来像默认 Asp.net WebAPI 模板中指定的那样(> vs2013)

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

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

确保您请求的 Url 与 MVC 或 WebAPI 路由模板匹配。