Watch this example on YouTube
1. Install NuGet
PM> Install-Package Microsoft.AspNet.WebApi.WebHost
PM> Install-Package Microsoft.AspNet.WebApi
2. Add to App_Start folder
using System.Web.Http;
namespace WebApplication17
{
public static class WebAppConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
}
3. Modify Global.asax
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
namespace WebApplication17
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
WebAppConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
4. Modify Layout file
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
</head>
5. Create empty controller
namespace WebApplication17.Controllers
{
public class TestController : System.Web.Http.ApiController
{
public string Get()
{
return "returning something";
}
}
}
6. Modify Home\Index file
@{
ViewBag.Title = "Home Page";
}
<script>
var url = '/api/test';
$(document).ready(function () {
$.ajax({
url: url,
async: true,
success: function (data) {
alert(data);
}
});
});
</script>
Great tips on creating a simple WebApiConfig in MVC! Just like DV Hosting enhances your hosting experience, this knowledge can simplify your app development.
ReplyDelete