Quick note adding Web API to existing application. Within Visual Studio, I’m starting from an empty MVC 4.0 application.
1. Add references:
- NewtonSoft.Json
- System.Net.Http
- System.Net.Formatting
- System.Web.Http
- System.Web.Http.WebHost
PM> Install-Package Microsoft.AspNet.WebApi.WebHost
Attempting to resolve dependency 'Microsoft.AspNet.WebApi.Core (≥ 5.1.2 && < 5.2.0)'.
Attempting to resolve dependency 'Microsoft.AspNet.WebApi.Client (≥ 5.1.2)'.
Attempting to resolve dependency 'Newtonsoft.Json (≥ 4.5.11)'.
Installing 'Microsoft.AspNet.WebApi.WebHost 5.1.2'.
Successfully installed 'Microsoft.AspNet.WebApi.WebHost 5.1.2'.
Adding 'Microsoft.AspNet.WebApi.Client 5.1.2' to .
Successfully added 'Microsoft.AspNet.WebApi.Client 5.1.2' to .
Adding 'Microsoft.AspNet.WebApi.Core 5.1.2' to .
Successfully added 'Microsoft.AspNet.WebApi.Core 5.1.2' to .
Adding 'Microsoft.AspNet.WebApi.WebHost 5.1.2' to .
Successfully added 'Microsoft.AspNet.WebApi.WebHost 5.1.2' to .
2. Within App_Start folder add WebApiConfig class:
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {
id = RouteParameter.Optional
});
}
}
3. Add to Global.asax.cs file:
using System.Web.Http;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
This post is for the purpose of my notes only.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford
No comments:
Post a Comment