Click here to Skip to main content
11,635,705 members (81,178 online)
Click here to Skip to main content

How to Self Host Web API 2 in ASP.NET Web Forms Application using OWIN

, 17 Dec 2014 CPOL 9.7K 5
Rate this:
Please Sign up or sign in to vote.
Self Host Web API 2 in ASP.NET web forms application using OWIN

Introduction

In this tip, we will learn how to Self Host Web API 2 in ASP.NET web forms application using OWIN.

Background

I have been working with WCF services and enjoyed how it can be easily self hosted for testing purposes. I explored the self hosting options for Web API and provided one of the ways here. I used Web API 2 and Framework 4.5 for this. OWIN self hosting may not work correctly for frameworks less than 4.5.

Using the Code

Create Web API Project

Let us start by creating a Web API 2 project. To do this, create a MVC 4 web application.

Select Empty in Project Template dialog. Select Empty template to avoid all the files that will be auto generated, which are out of the scope of this tip.

Solution explorer will have these:

Add an API controller to the Controllers folder. I named my controller as DataController. Make sure the Template is "Empty API controller".

Add the following methods to the controller (I took these from auto generated controller of Web API project for demo purposes, but you can add your own methods).

public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

public string Get(int id)
{
    return "value";
}

To install the supporting DLLs for enabling the Web API to be self hosted, we need to get all the required and dependent packages using NuGet Package Manager.Search for web-api and select "Microsoft ASP.NET Web API2.2 OWIN Self Host" and install the package.

After the packages are installed, build the solution. If you see the messages given in the below screenshot, you can solve it in two ways.

If you run the application without solving the above DLL version conflicts, you will get the below exception.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, 
Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. 
The located assembly's manifest definition does not match the assembly reference. 
(Exception from HRESULT: 0x80131040)

Method 1

Go to the Error list and double click on the warning message and select "Yes" in the dialog box to automatically add <assemblyBinding> to the config file.

Method 2

Manually add the below configuration in the config file.

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" 
publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" 
publicKeyToken="31BF3856AD364E35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" 
publicKeyToken="31BF3856AD364E35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>

After these changes, build and run the application. You may get the below exception this time. This is a different exception and it shows we are making progress Smile | :) .

Exception Details: System.TypeAccessException: Attempt by security transparent method 
'System.Web.Http.GlobalConfiguration.get_Configuration()' to access security critical type 
'System.Web.Http.HttpConfiguration' failed.

Run the below commands in NuGet console. For further details, please refer to this link.

Uninstall-Package Microsoft.AspNet.Mvc.FixedDisplayModes
Update-Package Microsoft.AspNet.WebApi -Pre

Again, build and run the application and go the Web API URL. Finally, the service is running Smile | :)

As a last thing, add a class in project root (I named it StartAPI), and add the below method in that class. The required namespaces are Owin and System.Web.Http.

public void Configuration(IAppBuilder appBuilder)
{
    HttpConfiguration config = new HttpConfiguration();
    WebApiConfig.Register(config);
    appBuilder.UseWebApi(config);
}

Now we are all done with the Web API project.

Create ASP.NET Web Forms Project to Host Web API

  1. Create an ASP.NET empty web application.
  2. Install the packages required for OWIN self hosting using NuGet package manager like we did for the Web API project. Just install the packages and build the project. There should not be any issues with DLLs.
  3. Add a reference to the Web API project that we created earlier.
  4. Add a Web form to the project. Add a button to the web form and in the click event handler, add the below code:
    protected void Button1_Click(object sender, EventArgs e)
    {
        string baseAddress = "http://localhost:8090/";
        using (WebApp.Start<StartAPI>(url: baseAddress))
        {
            Response.Write("Web API Self host server is up and running");
            HttpClient client = new HttpClient();
            var res = client.GetAsync(baseAddress + "api/data/1").Result;
            Response.Write("<br>");
            Response.Write(res.Content.ReadAsStringAsync().Result); 
        }
    }
  5. Run the application and click the button to see the results.

Points of Interest

In this tip, we have seen how to self host Web API using OWIN and how to solve the exceptions that may occur during the process. Hope this was informative and helpful.

History

  • 17th December, 2014: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mathi Mani
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150728.1 | Last Updated 17 Dec 2014
Article Copyright 2014 by Mathi Mani
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid