如何将 Web API 添加到现有的 ASP.NET MVC 4 Web 应用程序项目? [英] How to add Web API to an existing ASP.NET MVC 4 Web Application project?
问题描述
我希望将 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.
推荐答案
我需要执行的步骤是:
- 添加对
System.Web.Http.WebHost
的引用. - 添加
App_StartWebApiConfig.cs
(参见下面的代码片段). - 在
Global.asax.cs
中导入命名空间System.Web.Http
. - 在
MvcApplication.Application_Start()
(文件Global.asax.cs
)中调用WebApiConfig.Register(GlobalConfiguration.Configuration)
,之前注册默认的 Web 应用程序路由,否则将优先. - 添加从
System.Web.Http.ApiController
派生的控制器.
- Add reference to
System.Web.Http.WebHost
. - Add
App_StartWebApiConfig.cs
(see code snippet below). - Import namespace
System.Web.Http
inGlobal.asax.cs
. - Call
WebApiConfig.Register(GlobalConfiguration.Configuration)
inMvcApplication.Application_Start()
(in fileGlobal.asax.cs
), before registering the default Web Application route as that would otherwise take precedence. - Add a controller deriving from
System.Web.Http.ApiController
.
然后我可以从 教程(您的第一个 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_StartWebApiConfig.cs:
App_StartWebApiConfig.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 年 16 月 10 日更新:
Word 有,必须安装 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屋!