How to create Web Api in Asp.net web forms 4.0/4.5
2) Add Web Api Controller class
Name it as ValuesController.cs VS 2012 adds ValuesController1.cs remove 1 otherwise it won't work. i.e ApiController controller class must end with "Controller"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication3
{
public class ValuesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
3) Add Global.asax global class.
in Application_Start
add following namespaces( These Assemblies will be referenced automatically whenever u add Web Api Control class)
using System.Web.Http;
using System.Web.Routing;
4) in Application_start Global.asax
Add Routing information for WEB APIS.
4.1 "WebApi/{controller}" in this --> WebApi is a optional constant. User has his own choice of specifying it or not.
4.2 {contoller} is a keyword.(must be specified)
4.3 "Defaultapi" -> Routing table is dictionary so it must be unique across the web application.
user has choice of specify any value here.
Here is the code.
namespace WebApplication3
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configuration.Routes.MapHttpRoute("Defaultapi",
"WebApi/{controller}");
}
}
That's it
Just run the Web Application
Here is the URL to access WebAPI.
http://localhost:8899/WebApi/Values
1)change port number
2)WebApi constant specified in Routing tag.
if Routing url is "{controller}" then to access WebAPI through url
http://localhost:8899/Values
Note: Controller class can be Anywhere in the Web Application. i.e it can be even in nested folders. But Controller name should be unique unless specified by different routing values.
tags: How to create Web Api in asp.net Web forms,
Using Web API with ASP.NET Web Forms, Adding Web Api support to Web Forms,
How to access Web Api in asp.net web forms 4.0,