The steps I needed to perform were:
- Add reference to
System.Web.Http.WebHost
. - Add
App_Start\WebApiConfig.cs
(see code snippet below). - Import namespace
System.Web.Http
inGlobal.asax.cs
. - Call
WebApiConfig.Register(GlobalConfiguration.Configuration)
inMvcApplication.Application_Start()
(in fileGlobal.asax.cs
), before registering the default Web Application route as that would otherwise take precedence. - Add a controller deriving from
System.Web.Http.ApiController
.
I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.
App_Start\WebApiConfig.cs:
using System.Web.Http;
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
// To return objects in Json format (Not XML Format),
var appXmlType = configuration.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}
Global.asax.cs:
using System.Web.Http;
...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
No comments:
Post a Comment