假设您在制作一个新的MVC(5)项目时忘了勾选Web API复选框(将其添加到项目中),那么您需要做什么来添加Web API并使其工作呢?
有许多迁移问题,但似乎没有一个是完整的,最新的步骤来将Web API添加到MVC5项目中,而且似乎已经改变了一些旧的答案。
在MVC4中添加Web API
null
使用Nuget获取最新的Web API。
null
null
将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项目,它将具有global.asax.cs,请添加新路由。global.asax.cs路由的顺序非常关键。注意,有一些使用
将此行添加到global.asax.cs:
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帮助页面,请安装WebAPI.helppage。有关它的功能,请参阅http://channel9.msdn.com/events/build/2014/3-644(42分钟)。看起来很有帮助!
Nuget控制台:
到controllers文件夹-&>;添加新项目-&>;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()操作,它自动映射到methods/actions,这取决于其余的操作,例如put/post/GET/delete.您不需要像MVC那样通过操作调用它们)直接调用URL:
http://localhost:PORT/api/CONTROLLERNAME/
或者,使用jQuery查询控制器。运行项目,打开控制台(FIE中的F12)并尝试运行一个Ajax查询。(检查您的端口控制器名称(&Amp;CONTROLLERNAME)
$.get( "http://localhost:PORT/api/CONTROLLERNAME/", function( data ) {
//$( ".result" ).html( data );
alert( "Get data received:" + data);
});
附注:在项目中结合MVC和Web API时,需要考虑一些利弊
WebAPI帮助验证: