Build and Deploy Web Application and Web API as Azure Web App through VSO Continuous Integration

I thought to write this post which might help my fellow developers to know how to create a CI build for any web application or web API through Team Services of VSO. Just like in one of the post I have explained how we can create a NuGet package using CI build, this post might give more insight about building and deploying an web application directly to Azure using CI build. Let’s get through the steps involved.

Step 1: Install and configure Azure PowerShell

This step is highly important if you don’t have Azure PowerShell installed. The cmdlets of Azure PowerShell can be used to create/configure cloud apps/services, VM, virtual networks, etc. Download an install Azure PowerShell from this link.

Once installed open Windows PowerShell in administrative mode and run the following Azure PowerShell cmdlets to get details of your Azure subscription and resources available. Main that you need is your Subscription Name and Subscription Id.

Command to get Azure Account Information: Login-AzureRmAccount

image

Command to get Azure Resources available: Get-AzureRmResource

Command to get the Subscription Name and Id: Get-AzureRmSubscription

Command to get the Azure Publish Settings File: Get-AzurePublishSettingsFile

This command is important to get profile settings for publishing your web app in Azure. This will download the publish settings file along with the credentials in your local box.

SNAGHTML1b92cac

Step 2: Create New Service Endpoint in Team Services dashboard

This step will help us to register or add our Azure subscription to TFS. This is done only once and at collection level using the Service tab. Just select New Service Endpoint and select Azure Classic.

 

In Add New Azure Classic Connection choose Subscription Id and Subscription Name that you got from Azure Command Get-AzureRmSubscription. The Connection Name can be based on your preferred one. You can even open the downloaded Publish Settings file to get the Subscription Id and Subscription Name. Also from the file, copy the content of Management Certificate and paste it in place holder as shown below while creating the new Connection.

 

Now this service endpoint is ready to be used while publishing the azure web app.

Step 3: Configure the Build and Deployment properties of Team Project

Create the build definition file for the team project for which you want to instantiate the CI build at every check in process to source control. For that select Azure WebApp from the Deployment tab of Build Definition window.

 

As usual in Build definition created, update your Mapping information to point to source control repository of your solution in Repository Tab. Update your CI filter in Trigger tab to point to source control repository of your solution.

Next lets select the Build tab and select Azure Deployment. In details section, you need to select the new service endpoint created and select the Web App Name.

 

That’s all we need. Now you can queue the build to see how it works.

Owin.IAppBuilder does not contain definition for UseWebApi

At some point of time you might had encountered issues with Owin.IAppBuilder giving error in Startup class which states

‘Owin.IAppBuilder’ does not contain a definition for ‘UseWebApi’ and no extension method ‘UseWebApi’ accepting a first argument of type ‘Owin.IAppBuilder’ could be found (are you missing a using directive or an assembly reference?)

This basically happens when try to add route configuration to the OWIN pipeline while using ASP.NET Web API2 OWIN. You might try updating the OWIN package from 3.0.0.0 to 3.0.1.0 using the NuGet command update-package Microsoft.Owin but that will not resolve the issue.

Solution is you need to install Microsoft ASP.NET Web API2 OWIN Self Host which will resolve the issue. You can use the NuGet command Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

image

ServiceStack.Net – Developing Authentication Module using Auth0 and OAuthProvider to login using GMail, Twitter, Facebook account

I know you might be asking yourself what is Service Stack. Service Stack is a high performance .NET Web Service Framework that simplifies the development of XML, JSON, JSV and SOAP Web Services. It is also an open source, cross platform Mono Web Service framework which supports running Web Services built with Service Stack to run in Windows environment with .NET code or in Linux environment with Mono support. Hence Service Stack is an ideal option if we plan to build Web Services in .NET and deploy in environment other than windows. Service Stack enforces convention-based DTO standards  to its Web Service interface. It is a simple, fast, lightweight, testable and clean Web Service framework which has been build on top of raw ASP.NET IHttpHandlers. Following is the architecture of Service Stack.

image

You can learn more about Service Stack from here  https://servicestack.net/. You can install ServiceStack.Net through Nuget package explorer and there are lot of packages available within ServiceStack.Net based on your requirement like Advanced HTML support for MVC application, Message Queue Server integration, JSON Serializers and many more. I recommend you to give a try with this framework because I feel it will help you while you are building an Enterprise Application. I will try to cover many areas and implementation of ServiceStack.Net through various posts.

Today I am going to try to use ServiceStack.Net for implementing User Authentication and Authorization feature in a Web application built on top of MVC 5. Let’s get going.

First I am going to create a blank MVC Application without any authentication process in VS 2013. Run your application to check it is working properly once the project is created. Just a kind of verification from your side. I always do that.

image

Cool, let’s now try to understand what are the types of Authentication Providers we are going to use here. We are going to use built-in Authentication Providers, OpenId Authentication Providers and OAuth2 Providers. The Open-Id and OAuth2 providers are for using Google, Twitter, LinkedIn and Facebook authentication.

Let us first install ServiceStack framework for MVC through Package Manager Console using the Nuget Command Install-Package ServiceStack.Host.Mvc

PM> Install-Package ServiceStack.Host.Mvc
Attempting to resolve dependency 'WebActivator (≥ 1.5)'.
Attempting to resolve dependency 'Microsoft.Web.Infrastructure (≥ 1.0.0.0)'.
Attempting to resolve dependency 'ServiceStack.Mvc (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Common (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Interfaces (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Text (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Client (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Server (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Redis (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.OrmLite (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.OrmLite.SqlServer (≥ 4.0.33)'.

Once ServiceStack is installed, we will find few changes in our Project.

image

There are few changes in Web.Config file. Below are the changes you can see.

image

image

Next in order to register ServiceStacks “/api” path we need to add the below code in RegisterRoutes() of RouteConfig.cs file

public static void RegisterRoutes(RouteCollection routes)
{
//This is required for Service Stack
routes.IgnoreRoute("api/{*pathInfo}");

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

Update your Index() action in HomeController with the following code

public ActionResult Index()
{
//return View();
return Redirect("default.htm");
}

ServiceStack supports authorizing as a client via Google, Facebook, Twitter OAuth Servers. To use this facility we have to install OAuthProvider using the Nuget command Install-Package Auth0-ServiceStack-OAuthProvider.

PM> Install-package Auth0-ServiceStack-OAuthProvider
Attempting to resolve dependency 'ServiceStack (≥ 3.9.28)'.
Attempting to resolve dependency 'ServiceStack.Common (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Interfaces (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Text (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Client (≥ 4.0.33)'.
Installing 'Auth0-ServiceStack-OAuthProvider 0.0.2'.
Successfully installed 'Auth0-ServiceStack-OAuthProvider 0.0.2'.
Adding 'Auth0-ServiceStack-OAuthProvider 0.0.2' to ServiceStack.WebAuth.Demo2.
Successfully added 'Auth0-ServiceStack-OAuthProvider 0.0.2' to ServiceStack.WebAuth.Demo2.

This installation will add two classes in App_Start folder (Auth0Provider and Auth0UserSession).

image

Oh no…! Everything was fine till then. The project was compiling properly. But as soon as I have installed the OAuthProvider, the whole project was giving me lot of build errors. Not knowing what to do I tried to seek various ways to resolve the issues but unfortunately no resolution was found. At last through one of the forum, I found I need to install ServiceStack of version 3.9.71 through Nuget.

Hence I Uninstalled all the packages ServiceStack, ServiceStack.Host.Mvc and Auth0.ServiceStack.OAuthProvider at first place. Cleaned the solution at earliest. Next I ran the following commands to install back these packages except OAuthProvider in specific version 3.9.71 through Nuget Command.

Install-Package ServiceStack -Version 3.9.71

Install-Package ServiceStack.Host.Mvc -Version 3.9.71

Install-Package Auth0-ServiceStack-OAuthProvider

Awesome now I am not getting any build errors and things are in place.

Now our next step is to enable Authentication and plug in Auth0’s provider. Let’s open the file AppHost.cs generated by ServiceStack and uncomment the following lines in Configure() Method.

image

Now update the method ConfigureAuth() with following lines of code as shown below.

image

Ok my final piece of code for ConfigureAuth() is here

/* Uncomment to enable ServiceStack Authentication and CustomUserSession*/
private void ConfigureAuth(Funq.Container container)
{
var appSettings = new AppSettings();

Plugins.Add(new AuthFeature(
() => new Auth0UserSession(),
new IAuthProvider[] {
new Auth0Provider(appSettings, appSettings.GetString("oauth.auth0.OAuthServerUrl"))
}));


//var appSettings = new AppSettings();

//Default route: /auth/{provider}
//Plugins.Add(new AuthFeature(() => new CustomUserSession(),
// new IAuthProvider[] {
// new CredentialsAuthProvider(appSettings),
// new FacebookAuthProvider(appSettings),
// new TwitterAuthProvider(appSettings),
// new BasicAuthProvider(appSettings),
// }));

//Default route: /register
//Plugins.Add(new RegistrationFeature());

//Requires ConnectionString configured in Web.Config
//var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;
//container.Register<IDbConnectionFactory>(c =>
// new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));

//container.Register<IUserAuthRepository>(c =>
// new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

//var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>();
//authRepo.CreateMissingTables();
}

We are not doing any User Registration here, so we have commented out the lines required for User Registration

Well our next step is to register the OAuth Url in Application Settings section, since after authenticating the user on Auth0 we would do a POST to a URL on our web site. So let’s go ahead and modify our Web.Config accordingly.

image

Now here I will explain you what is required to be done. First create a free account of yours in https://auth0.com.

image

 image

image

Once your email is verified, next step is to select the type of App you are integrating Auth0. For me I have selected Regular Web App.

image

Then You will get a screen where you need to select the Platform we are using in the App. I am selecting ServiceStack.

image

Once selected, the next screen is going to provide you the three Auth0 parameters which are (oauth.auth0.AppId, oauth.auth0.AppSecret and oauth.auth0.OAuthServerUrl). Copy the values and paste them in the Web.Config file against the AppSettings keys you have specified.

Now copy this JavaScript code in your _Layout.cshtml file. The Auth0Lock parameter should have your oauth.auth0.AppId followed by oauth.auth0.OAuthServerUrl. You can get the values from your Web.Config file. Also the callbackUrl should have the port number if any is used for running your application

https://cdn.auth0.com/js/lock-6.2.min.js

var lock = new Auth0Lock('vs4n82A6wLrmViah2QW2IWM8pSV8mCbe', 'idevexplorer.auth0.com');

function signin() {
lock.show({
callbackURL: 'http://localhost:4678/api/auth/auth0/'
, responseType: 'code'
, authParams: {
scope: 'openid profile'
}
});
}

Now place a Sign In link in your Navigational Panel of _Layout.cshtml file


Once done run your application and click on the Sign In link. You will be able to see the following Auth0 popup window.

image

Hold on, things are done yet. Now we need to ensure that once the User is successful in login through Auth0 then all related information is available in our web application. So what we are going to do here is first login to Auth0  site and go to Settings section of Default app. Update the Callback URL of your application like http://localhost:4678/api/auth/auth0/ which is specified in you JavaScript block of SignIn() method

image

Now lets modify  our Index.cshtml by placing a div over the top which will be the placeholder of the information grabbed from Auth0.


User Info:
Not logged in

And then we are going to update our _Layout.cshtml file adding a script block to render “userInfo” code template with the data retrieved from the authentication module.

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

$(function () {
$.getJSON('/api/hello', function (data) {
$("#content").is(":hidden");
$('#userInfo').text(JSON.stringify(data.userInfo, 1, 2));
});
});

Great, let’s go ahead and now run the application. And then try to login through Goggle account. You can see the result as below which will be rendered in “userInfo code block

image

Try with various options for logging into the application. I hope you will like this article and this will provide a platform for you to start with  Auth0 authentication integration using ServiceStack in future.

.NET Web API in MVC 5 Areas with Api Help and Dependency Injection

I was trying to find out the best possible way to  create .NET Web API with the API Controller specific to ASPNET MVC 5 areas. I went through various blogs and articles and finally found one of the blog written by  Andrew Malkov  and it really helped me a lot. My next step is to use Dependency Injection using Unity and also provide a Help page for the API. The Help Link for creating the Help page was really useful for me.

I am sharing with you how I went up on implementing the same. Following are the activities that I have to work on

  • Create an MVC + API project in Visual Studio 2013
  • Create a PCL (Portable Class Library) project in solution
  • Create a model, interface and implementation in Portable Class Library
  • Add Areas in MVC project implementing Web API Controller
  • Implement Dependency Injection using Unity for Web API Controller
  • Implement Help Library for the API in MVC View

Create an MVC + API project in Visual Studio 2013

WebApi

Create an Portable Class Library (PCL) project in Visual Studio 2013 for Business Layer

Once the Application is created lets go ahead to add Portable Class Library (PCL) project to the same solution. Portable Class Library are used for importing libraries compatible to multiple device. This library will have the business logic with a model, an Interface and an implementation.

Following is my model object for Product

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

Creating an Interface for Product Business Layer

public interface IProductService
{
    IEnumerable<Product> GetAllProducts();
    Product GetProduct(int id);
}

Implementation of the Interface in PCL Business library

public class ProductService : IProductService
{
    public IEnumerable<Product> GetAllProducts()
    {
        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };
        return products;
    }

    public Product GetProduct(int id)
    {
        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };
        var product = products.FirstOrDefault((p) => p.Id == id);
        return product;
    }

That’s it we are done with the PCL implementation. We are going to add the reference of this PCL in our MVC project

Implement Dependency Injection using Unity in MVC project

In order to accomplish this aspect, install the package Unity through NuGet Package Manager Console for MVC Web Application

PM> install-package unity
Installing 'Unity 3.5.1404.0'.
You are downloading Unity from Microsoft, the license agreement to which is available at http://opensource.org/licenses/Apache-2.0. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Unity 3.5.1404.0'.
Adding 'Unity 3.5.1404.0' to WebApi.Demo1.
Successfully added 'Unity 3.5.1404.0' to WebApi.Demo1.

Next step is to a Unity Dependency Resolver in the project. Create a Resolver class and add the same in the project.

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;
    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }
    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public void Dispose()
    {
        container.Dispose();
    }
}

Now register the Unity container for WebApiConfig.cs file under App_Start folder. Add the types for the container. Here the type will be for Product Service created in Business Layer.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var container = new UnityContainer();
        container.RegisterType<IProductService, ProductService>(new HierarchicalLifetimeManager());
        config.DependencyResolver = new UnityResolver(container);
        // Web API routes
        config.MapHttpAttributeRoutes();

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

Now next step is to create an Area named Product and implement an Web API Controller integrating the business logic layer service.

public class ProductsController : ApiController
{
    private readonly IProductService _service;
    public ProductsController(IProductService Service)
    {
        _service = Service;
    }
    public IEnumerable<Product> GetAllProducts()
    {
        return _service.GetAllProducts();
    }

    public IHttpActionResult GetProduct(int id)
    {
        var product = _service.GetProduct(id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }


}

Once this is completed, our next step is to have the Web Api Controller recognized from MVC areas. For that we need to implement a AreaHttpControllerSelector that will be registered in WebAPI Area Config.

public class AreaHttpControllerSelector : System.Web.Http.Dispatcher.DefaultHttpControllerSelector
{
    private const string ControllerSuffix = "Controller";
    private const string AreaRouteVariableName = "area";

    private readonly System.Web.Http.HttpConfiguration _configuration;

    private Dictionary<string, Type> _apiControllerTypes;

    public AreaHttpControllerSelector(HttpConfiguration configuration)
        : base(configuration)
    {
        _configuration = configuration;
    }

    private Dictionary<string, Type> ApiControllerTypes
    {
        get { return _apiControllerTypes ?? (_apiControllerTypes = GetControllerTypes()); }
    }

    private static Dictionary<string, Type> GetControllerTypes()
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();

        var types = assemblies.SelectMany(a => a.GetTypes().Where(t => !t.IsAbstract && t.Name.EndsWith(ControllerSuffix) && typeof(IHttpController).IsAssignableFrom(t)))
            .ToDictionary(t => t.FullName, t => t);

        return types;
    }

    public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
    {
        return GetApiController(request) ?? base.SelectController(request);
    }

    private static string GetAreaName(HttpRequestMessage request)
    {
        var data = request.GetRouteData();

        if (!data.Values.ContainsKey(AreaRouteVariableName))
        {
            return null;
        }

        return data.Values[AreaRouteVariableName].ToString().ToLower();
    }

    private Type GetControllerTypeByArea(string areaName, string controllerName)
    {
        var areaNameToFind = string.Format(".{0}.", areaName.ToLower());
        var controllerNameToFind = string.Format(".{0}{1}", controllerName, ControllerSuffix);

        return ApiControllerTypes.Where(t => t.Key.ToLower().Contains(areaNameToFind) && t.Key.EndsWith(controllerNameToFind, StringComparison.OrdinalIgnoreCase))
                .Select(t => t.Value).FirstOrDefault();
    }

    private HttpControllerDescriptor GetApiController(HttpRequestMessage request)
    {
        var controllerName = base.GetControllerName(request);

        var areaName = GetAreaName(request);
        if (string.IsNullOrEmpty(areaName))
        {
            return null;
        }

        var type = GetControllerTypeByArea(areaName, controllerName);
        if (type == null)
        {
            return null;
        }

        return new HttpControllerDescriptor(_configuration, controllerName, type);
    }


}

Update the RegisterArea method with the following code and comment the previous code block

public class TestAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Test";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        //context.MapRoute(
        //    "Test_default",
        //    "Test/{controller}/{action}/{id}",
        //    new { action = "Index", id = UrlParameter.Optional }
        //);
        context.Routes.MapHttpRoute(
            name: "Admin_Api",
            routeTemplate: "api/admin/{controller}/{id}",
            defaults: new { area = "admin", id = RouteParameter.Optional }
        );

    }
}

Add the following line of code in Application_Start() of Global.asax.cs file

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new AreaHttpControllerSelector(GlobalConfiguration.Configuration));

That’s all done from the implementation aspect of WebAPI Controller in MVC 5 Areas.

Implement a HELP section for the API

In order to have a Help section for our API, install Microsoft.AspNet.WebApi.HelpPage using NuGet Package Manager Console in API Project.

PM> install-package Microsoft.AspNet.WebApi.HelpPage
Attempting to resolve dependency 'Microsoft.AspNet.WebApi.WebHost (= 5.2.2 && < 5.3.0)'.
Attempting to resolve dependency 'Microsoft.AspNet.WebApi.Core (= 5.2.2 && < 5.3.0)'.
Attempting to resolve dependency 'Microsoft.AspNet.WebApi.Client (= 5.2.2)'.
Attempting to resolve dependency 'Newtonsoft.Json (= 6.0.4)'.
Attempting to resolve dependency 'Microsoft.AspNet.Mvc (= 5.2.2 && < 5.3.0)'.
Attempting to resolve dependency 'Microsoft.AspNet.WebPages (= 3.2.2 && < 3.3.0)'.
Attempting to resolve dependency 'Microsoft.Web.Infrastructure (= 1.0.0.0)'.
Attempting to resolve dependency 'Microsoft.AspNet.Razor (= 3.2.2 && < 3.3.0)'.
Installing 'Newtonsoft.Json 6.0.5'.
Successfully installed 'Newtonsoft.Json 6.0.5'.
Installing 'Microsoft.AspNet.WebApi.Client 5.2.2'.
You are downloading Microsoft.AspNet.WebApi.Client from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.WebApi.Client 5.2.2'.
Installing 'Microsoft.AspNet.WebApi.Core 5.2.2'.
You are downloading Microsoft.AspNet.WebApi.Core from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.WebApi.Core 5.2.2'.
Installing 'Microsoft.AspNet.WebApi.WebHost 5.2.2'.
You are downloading Microsoft.AspNet.WebApi.WebHost from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.WebApi.WebHost 5.2.2'.
Installing 'Microsoft.AspNet.Razor 3.2.2'.
You are downloading Microsoft.AspNet.Razor from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.Razor 3.2.2'.
Installing 'Microsoft.AspNet.WebPages 3.2.2'.
You are downloading Microsoft.AspNet.WebPages from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.WebPages 3.2.2'.
Installing 'Microsoft.AspNet.Mvc 5.2.2'.
You are downloading Microsoft.AspNet.Mvc from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.Mvc 5.2.2'.
Installing 'Microsoft.AspNet.WebApi.HelpPage 5.2.2'.
You are downloading Microsoft.AspNet.WebApi.HelpPage from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.WebApi.HelpPage 5.2.2'.
Removing 'Microsoft.AspNet.WebApi.WebHost 5.0.0' from WebApi.Demo1.
Successfully removed 'Microsoft.AspNet.WebApi.WebHost 5.0.0' from WebApi.Demo1.
Removing 'Microsoft.AspNet.WebApi.Core 5.0.0' from WebApi.Demo1.
Successfully removed 'Microsoft.AspNet.WebApi.Core 5.0.0' from WebApi.Demo1.
Removing 'Microsoft.AspNet.WebApi.Client 5.0.0' from WebApi.Demo1.
Successfully removed 'Microsoft.AspNet.WebApi.Client 5.0.0' from WebApi.Demo1.
Removing 'Newtonsoft.Json 5.0.6' from WebApi.Demo1.
Successfully removed 'Newtonsoft.Json 5.0.6' from WebApi.Demo1.
Adding 'Newtonsoft.Json 6.0.5' to WebApi.Demo1.
Successfully added 'Newtonsoft.Json 6.0.5' to WebApi.Demo1.
Adding 'Microsoft.AspNet.WebApi.Client 5.2.2' to WebApi.Demo1.
Successfully added 'Microsoft.AspNet.WebApi.Client 5.2.2' to WebApi.Demo1.
Adding 'Microsoft.AspNet.WebApi.Core 5.2.2' to WebApi.Demo1.
Successfully added 'Microsoft.AspNet.WebApi.Core 5.2.2' to WebApi.Demo1.
Adding 'Microsoft.AspNet.WebApi.WebHost 5.2.2' to WebApi.Demo1.
Successfully added 'Microsoft.AspNet.WebApi.WebHost 5.2.2' to WebApi.Demo1.
Removing 'Microsoft.AspNet.Mvc 5.0.0' from WebApi.Demo1.
Successfully removed 'Microsoft.AspNet.Mvc 5.0.0' from WebApi.Demo1.
Removing 'Microsoft.AspNet.WebPages 3.0.0' from WebApi.Demo1.
Successfully removed 'Microsoft.AspNet.WebPages 3.0.0' from WebApi.Demo1.
Removing 'Microsoft.AspNet.Razor 3.0.0' from WebApi.Demo1.
Successfully removed 'Microsoft.AspNet.Razor 3.0.0' from WebApi.Demo1.
Adding 'Microsoft.AspNet.Razor 3.2.2' to WebApi.Demo1.
Successfully added 'Microsoft.AspNet.Razor 3.2.2' to WebApi.Demo1.
Adding 'Microsoft.AspNet.WebPages 3.2.2' to WebApi.Demo1.
Successfully added 'Microsoft.AspNet.WebPages 3.2.2' to WebApi.Demo1.
Adding 'Microsoft.AspNet.Mvc 5.2.2' to WebApi.Demo1.
Successfully added 'Microsoft.AspNet.Mvc 5.2.2' to WebApi.Demo1.
Adding 'Microsoft.AspNet.WebApi.HelpPage 5.2.2' to WebApi.Demo1.
Successfully added 'Microsoft.AspNet.WebApi.HelpPage 5.2.2' to WebApi.Demo1.
Uninstalling 'Microsoft.AspNet.WebApi.WebHost 5.0.0'.
Successfully uninstalled 'Microsoft.AspNet.WebApi.WebHost 5.0.0'.
Uninstalling 'Microsoft.AspNet.WebApi.Core 5.0.0'.
Successfully uninstalled 'Microsoft.AspNet.WebApi.Core 5.0.0'.
Uninstalling 'Microsoft.AspNet.WebApi.Client 5.0.0'.
Successfully uninstalled 'Microsoft.AspNet.WebApi.Client 5.0.0'.
Uninstalling 'Newtonsoft.Json 5.0.6'.
Successfully uninstalled 'Newtonsoft.Json 5.0.6'.
Uninstalling 'Microsoft.AspNet.Mvc 5.0.0'.
Successfully uninstalled 'Microsoft.AspNet.Mvc 5.0.0'.
Uninstalling 'Microsoft.AspNet.WebPages 3.0.0'.
Successfully uninstalled 'Microsoft.AspNet.WebPages 3.0.0'.
Uninstalling 'Microsoft.AspNet.Razor 3.0.0'.
Successfully uninstalled 'Microsoft.AspNet.Razor 3.0.0'.

Once successfully installed following folder structure can be found.

HelpPage

Open the HelpPageConfig.cs under Areas\HelpPage\App_Start folder and uncomment the line

config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

Now add a link API in _Layout.cshtml to get the Help Page in the Navigational Panel

<li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>

That’s it your help page is ready. Below is the sample screenshot of the page

APIhelp

Before running the API help, change the Build Property Settings of the API project. Add the below settings highlighted.

Build Property

That’s all for using Web API in MVC 5 Areas. Happy Coding….