更新 MVC 项目
Use Nuget获取最新的 Web API。
项目 - 右键 - 管理 Nuget 包 - 搜索 Web API(Microsoft ASP.NET Web API ...)并将其安装到您的 MVC 项目中。
那么你还需要得到Web API 路由上班。
从Microsoft 的配置 ASP.NET Web API 2 http://www.asp.net/web-api/overview/advanced/configuring-aspnet-web-api
将WebApiConfig.cs添加到App_Start/文件夹中
using System.Web.Http;
namespace WebApplication1
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// TODO: Add any additional configuration code.
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// WebAPI when dealing with JSON & JavaScript!
// Setup json serialization to serialize classes to camel (std. Json format)
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
}
}
如果您有一个 MVC 项目,它将有全局.asax.cs,添加新路线。Global.asax.cs 路由的顺序至关重要。 https://stackoverflow.com/questions/22401403/add-web-api-to-an-existing-mvc-5-web-application请注意,有一些过时的示例使用WebApiConfig.Register
将此行添加到 Global.asax.cs:
GlobalConfiguration.Configure(WebApiConfig.Register);
protected void Application_Start()
{
// Default stuff
AreaRegistration.RegisterAllAreas();
// Manually installed WebAPI 2.2 after making an MVC project.
GlobalConfiguration.Configure(WebApiConfig.Register); // NEW way
//WebApiConfig.Register(GlobalConfiguration.Configuration); // DEPRECATED
// Default stuff
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
WebAPI帮助
为了得到 (very) 有用的 WebAPI 帮助页面 http://www.asp.net/web-api/overview/creating-web-apis/creating-api-help-pages,安装WebAPI.HelpPage。
看http://channel9.msdn.com/Events/Build/2014/3-644 http://channel9.msdn.com/Events/Build/2014/3-644(约 42 分钟)了解它的作用。看起来很有帮助!
Nuget 控制台:Install-Package Microsoft.AspNet.WebApi.HelpPage
要验证 WebAPI 是否正常工作:
到控制器文件夹 -> 添加新项目 -> Web API 控制器类。
public class TestController : ApiController
{
//public TestController() { }
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
//...
}
现在您可以像往常一样在 IE/FF/Chrome 中进行测试,或者在 JavaScript 控制台中进行非 get 测试。
(仅使用 URL 中的控制器,它将在新的 Web API 控制器中调用 GET() 操作,它会根据 REST 自动映射到方法/操作,例如 PUT/POST/GET/DELETE。您无需调用像 MVC 中那样通过操作来实现)
直接网址:
http://localhost:PORT/api/CONTROLLERNAME/
或者使用 jQuery 查询控制器。
运行项目,打开控制台(IE 中的 F12)并尝试运行 Ajax 查询。 (检查您的端口和控制器名称)
$.get( "http://localhost:PORT/api/CONTROLLERNAME/", function( data ) {
//$( ".result" ).html( data );
alert( "Get data received:" + data);
});
旁注:在项目中组合 MVC 和 Web API 时需要考虑一些优缺点 https://stackoverflow.com/questions/12905566/web-api-in-mvc-solution-in-separate-project
WebAPI帮助验证:
http://localhost:PORT/help