Web Api Without MVC

Download full source code.

When building a Web Api 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 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

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

WebApiConfig.cs

public static class WebApiConfig
{
    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 }
        );
    }
}

ValuesController.cs

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] {$"Guid 1: {Guid.NewGuid()}", $"Guid 2: {Guid.NewGuid()}" };
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *