Web Api 2 Without MVC

Download full source code.

When building a Web Api 2 application there is much unneeded MVC baggage that comes along with it.

To start with all the css, html and javascript can go, then most of the packages, most of referenced dlls and almost all the C#.

Here are side by side comparisons of what you get and what you need.

All you really need for Web Api 2 is is the Global.asax to call WebApiConfig.Register which sets up the default routes and then a controller to perform an action.

Global.asax

1public class WebApiApplication : System.Web.HttpApplication
2{
3    protected void Application_Start()
4    {
5        GlobalConfiguration.Configure(WebApiConfig.Register);
6    }
7}

WebApiConfig.cs

 1public static class WebApiConfig
 2{
 3    public static void Register(HttpConfiguration config)
 4    {
 5        // Web API routes
 6        config.MapHttpAttributeRoutes();
 7
 8        config.Routes.MapHttpRoute(
 9            name: "DefaultApi",
10            routeTemplate: "api/{controller}/{id}",
11            defaults: new { id = RouteParameter.Optional }
12        );
13    }
14}

ValuesController.cs

1public class ValuesController : ApiController
2{
3    // GET api/values
4    public IEnumerable<string> Get()
5    {
6        return new string[] {$"Guid 1: {Guid.NewGuid()}", $"Guid 2: {Guid.NewGuid()}" };
7    }
8}
comments powered by Disqus

Related