Create Web API from scratch


1. Create new project by selecting Asp.Net web application with Empty template

Add Web API references using NuGet Package Manager. Right Click on the project and click Manage NuGet Packages, and search 'Microsoft ASP.NET Web API' and click on Install
(This package contains everything you need to host ASP.NET Web API on IIS)


2. Create two folders, "Controllers" and "Configuration" by right clicking on the project.

3. Add new class 'DemoWebAPIConfig' in the "configuration" folder

4. Add below code in it

using System.Web.Http
public static class DemoWebAPIConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

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


5. Add global.asax by right clicking on the project 

using System.Web.Http
 protected void Application_Start(object sender, EventArgs e)
    {
        GlobalConfiguration.Configure(DemoWebAPIConfig.Register);
    }

6. Create Web API controller by right clicking on the Controllers folder and select Controller , then choose the scaffold "Web API 2 Controller - Empty'.
   Enter controller name  'DemoController' and click Add.


public class DemoController : ApiController
    {
       
    }

7. Add Action method 'Get' as below

      public string Get()
        {
            return "welcome";
        }

8.compile and run the project and navigate to http://localhost:xxxx/api/demo in the browser (xxxx is the port number). it displays the result. 

No comments:

Post a Comment