MVC 5,Web API和Owin

Ste*_*tes 4 .net c# asp.net-mvc asp.net-web-api 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);
}
Run Code Online (Sandbox Code Playgroud)

是RouteConfig.RegisterRoutes(RouteTable.Routes)吗?

每当我浏览任何MVC路线时,我都会获得404.

rob*_*ich 8

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


ven*_*mit 1

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

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

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

是的,这适用于 Asp.net MVC,但对于 Web api,您需要在单独的配置类中注册路由。通常 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 }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

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