Thursday, November 3, 2016

Create WebAPI application with an empty template


Creating a WebAPI application in Visual Studio using the templates available makes it bloated with tons of nuget package references and other stuff. Following are the steps to make a WebAPI application in Visual Studio with an empty website template.


1) Create an empty Web Application with nothing in it. (no Global asax, no entry in web.config, no JS)


2) Add Microsoft.AspNet.WebApi.WebHost nuget package to the project. This will add the other dependent packages like WebApi.Core etc.

3) Add a Global.asax file and insert these lines
        protected void Application_Start(object sender, EventArgs e)
        {            
            WebApiConfig.Register(GlobalConfiguration.Configuration);
        }

4) Add a App_Start folder with WebApiConfig.cs
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

5) Add folder - "Controllers"

6) Add HomeController with the following code - 

 public class HomeController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

    }

No comments:

Post a Comment