To add WebAPI in my MVC 5 project.
Open NuGet Package manager console and run
PM> Install-Package Microsoft.AspNet.WebApi
Add references to System.Web.Routing
, System.Web.Net
and System.Net.Http
dlls if not there already
Right click controllers folder > add new item > web > Add Web API controller
Web.config will be modified accordingly by VS
Add Application_Start
method if not there already
protected void Application_Start()
{
//this should be line #1 in this method
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Add the following class (I added in global.asax.cs file)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Modify web api method accordingly
namespace <Your.NameSpace.Here>
{
public class VSController : ApiController
{
// GET api/<controller> : url to use => api/vs
public string Get()
{
return "Hi from web api controller";
}
// GET api/<controller>/5 : url to use => api/vs/5
public string Get(int id)
{
return (id + 1).ToString();
}
}
}
Rebuild and test
Build a simple html page
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../<path_to_jquery>/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var uri = '/api/vs';
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
alert('got: ' + data);
});
$.ajax({
url: '/api/vs/5',
async: true,
success: function (data) {
alert('seccess1');
var res = parseInt(data);
alert('got res=' + res);
}
});
});
</script>
</head>
<body>
....
</body>
</html>