将Web API添加到现有MVC Web应用程序后出现404错误

Lui*_*eia 60 c# asp.net rest asp.net-mvc asp.net-web-api

这里有一个很好的问题: 如何将Web API添加到现有的ASP.NET MVC 4 Web应用程序项目中?

不幸的是,这还不足以解决我的问题.我已经尝试了两次,以确保我没有做错任何事.我右键单击"控制器"并添加了项目"Web API 2 Controller with actions,using Entity Framework",其中我选择了我的模型类和db上下文.一切都很顺利...但仍然...每次我试图访问/ api/Rest我得到404错误(我的控制器的名称是RestController).

Lui*_*eia 119

它的工作!!! 我不想相信,但猜猜是什么,问题与Global.asax路由顺序有关.

虽然它不适用于:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    GlobalConfiguration.Configure(WebApiConfig.Register); //I AM THE 4th
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}      
Run Code Online (Sandbox Code Playgroud)

它适用于:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register); //I AM THE 2nd
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}      
Run Code Online (Sandbox Code Playgroud)

疯了,我知道.

  • api路由必须首先进行评估,或者你需要创建更严格的mvc路由(这样框架不会尝试查找'ApiController'.)这不是MVC5特有的行为. (13认同)
  • 请将您的答案标记为“可接受的答案”。 (2认同)

Moh*_*yan 5

如果您想在现有的 MVC (5) 项目中使用 WebAPI,您必须执行以下步骤:
1.添加 WebApi 包:

Microsoft.AspNet.WebApi
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi.WebHost
Newtonsoft.Json
Run Code Online (Sandbox Code Playgroud)

2.将WebApiConfig.cs文件添加到App_Start文件夹:

using System.Web.Http;

namespace WebApiTest
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // 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)

3.将以下行添加到Glabal.asax

GlobalConfiguration.Configure(WebApiConfig.Register);
Run Code Online (Sandbox Code Playgroud)

重要提示:您必须在上面添加一行AreaRegistration.RegisterAllAreas();

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    //\\
    GlobalConfiguration.Configure(WebApiConfig.Register);
    //\\
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Run Code Online (Sandbox Code Playgroud)