如何对Web API添加到现有的ASP.NET MVC 4 Web应用程序项目? [英] How to add Web API to an existing ASP.NET MVC 4 Web Application project?

查看:178
本文介绍了如何对Web API添加到现有的ASP.NET MVC 4 Web应用程序项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个的ASP.NET Web API 添加到ASP.NET MVC 4 Web应用程序项目,在开发Visual Studio的2012年。我必须执行哪些步骤,以一个正常运作的Web API添加到项目中?我知道,我需要一个控制器从ApiController派生,但是这就是所有我知道了。

I wish to add an ASP.NET Web API to an ASP.NET MVC 4 Web Application project, developed in Visual Studio 2012. Which steps must I perform to add a functioning Web API to the project? I'm aware that I need a controller deriving from ApiController, but that's about all I know.

让我知道如果我需要提供更多的细节。

Let me know if I need to provide more details.

推荐答案

我需要执行的步骤是:


  1. 添加引用 System.Web.Http.WebHost

  2. 添加 App_Start \\ WebApiConfig.cs (见下文code段)。

  3. 导入命名空间 System.Web.Http 的Global.asax.cs

  4. 呼叫 WebApiConfig.Register(GlobalConfiguration.Configuration) MvcApplication.Application_Start()(在文件的Global.asax.cs )的的注册默认Web应用程序的路由,否则将采取precedence。

  5. 添加控制器从 System.Web.Http.ApiController 导出。

  1. Add reference to System.Web.Http.WebHost.
  2. Add App_Start\WebApiConfig.cs (see code snippet below).
  3. Import namespace System.Web.Http in Global.asax.cs.
  4. Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
  5. Add a controller deriving from System.Web.Http.ApiController.

然后我可以从<一个学习不够href=\"http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api\">the教程(你的第一个的ASP.NET Web API)来定义我的API控制器。

I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.

App_Start \\ WebApiConfig.cs:

App_Start\WebApiConfig.cs:

using System.Web.Http;

class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });
    }
}

的Global.asax.cs:

Global.asax.cs:

using System.Web.Http;

...

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

更新2015年10月16日:

有传言,该包的NuGet Microsoft.AspNet.WebApi必须安装上述工作。

Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.

这篇关于如何对Web API添加到现有的ASP.NET MVC 4 Web应用程序项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆