So I needed to add a WebAPI to an existing MVC.net 5 web application. I also needed to add Authorization and hook into the existing security model. Here's the steps I took.

Install the Nuget Package

From the Package Manager Console:

Install-Package Microsoft.AspNet.WebApi

Check your Refs

Make sure in your References you have:

  • System.Web.Http

Add the Web API Config

Add a file App_Start\WebApiConfig.cs:

using System.Web.Http;

namespace Website.App_Start
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultActionApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = "Get", id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Update the global.asax.cs:
Add GlobalConfiguration.Configure(WebApiConfig.Register); after AreaRegistration.RegisterAllAreas();

Custom Authorisation Attribute

I needed to use a custom attribute in order to hook into the existing security model, however you may be able to use AuthorizeAttribute.

Create a class called WebApiAuthorizeAttribute.cs:

using System;
using System.Web.Http.Controllers;
using System.Linq;

namespace Website.API
{
    /// <summary>
    /// Custom Authorization Attribute for Web API
    /// </summary>
    /// <remarks>
    /// This works with the System.Web.Http namespace.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class WebApiAuthorizeRolesAttribute : System.Web.Http.AuthorizeAttribute
    {
        public WebApiAuthorizeRolesAttribute(params string[] roles) : base()
        {
            Roles = string.Join(",", roles);
        }
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            // Run Custom Authorisation Check
            bool authorised = false;
            ... Add your authorization logic here.

            return authorised;
        }
    }
}

Adding a Web API Controller:

First create a folder API at the root of the project.
Add a file API\SweetasController.cs

using System.Web.Http;

namespace Website.API
{
    [WebApiAuthorizeRoles("UserRole")]
    public class SweetasController : ApiController
    {
        public string Get()
        {
            return "Bro";
        }
    }
}

It's important to verify this works. Originally I had the attribute in another assembly, and for some reason the IsAuthorized override never got called and the authorize check was bypassed. Probably something to do with the references, but in the end it was quicker just to keep this attribute in the Website project.