ASP.NET MVC > Web API

Create ASP.NET Web API Controller in ASP.NET MVC

How to create an ASP.NET Web API Controller?


An ASP.NET Web API Controller can be created either in the normal ASP.NET MVC project by following below steps

Right click the Controllers folder and select Add > Controller…

In the above dialog box, select “Web API 2 Controller with actions, using Entity Framework”.

Now select the Model class, Data context and Controller name. If we want to create asynchronous controller, then we need to check the “User async controller actions” checkbox.

Clicking Add button adds a controller in the Controllers folder. Notice that this controller is inherited with ApiController class.

CONTROLLER CODE

     
public class PersonalDetailsAPIController : ApiController
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: api/PersonalDetailsAPI
     public IQueryable<PersonalDetail> GetPersonalDetails()
     {
            return db.PersonalDetails;
     }
     
     // GET: api/PersonalDetailsAPI/5
     [ResponseType(typeof(PersonalDetail))]
     public IHttpActionResult GetPersonalDetail(int id)
     {
         PersonalDetail personalDetail = db.PersonalDetails.Find(id);
         if (personalDetail == null)
         {
             return NotFound();
         }

         return Ok(personalDetail);
     }
   // more action method follows ......

}

Apart from this, we also get a WebApiConfig.cs file in the ~/App_Start folder where a default route for the api controller url is registered. Now, any url starting with “api/” will be routed through this route.

~/APP_START/WEBAPICONFIG.CS

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Now, in order to register/configure this route, we need to add following highlighted line of code inside the Application_Start event of the Global.asax.cs file.

GLOBAL.ASAX.CS

protected void Application_Start()
  {
      AreaRegistration.RegisterAllAreas();

      System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);

      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
  }

Once everything is configured, run the project and try to browse the url something like

             http://localhost:54003/api/PersonalDetailsAPI/

and we will notice that, the browser is asking to download the .json file returned by the Index method of the PersonalDetailsAPI controller as Web API returns json content by default.

This shows that our API is working fine and ready to use.


 Views: 25634 | Post Order: 121



Write for us






Hosting Recommendations