Using ASP.NET Web API with ASP.NET Web Forms


Several of the ASP.NET Web API tutorials (see for example “Your First ASP.NET Web API”) show how you can use ASP.NET Web API with MVC applications. However, you can equally well add a Web API to a Web Form enabling the same Web API support as in MVC applications.

To show how you do this, let’s build a Web Site from scratch and then add a Web API to it. We use the Visual Web Developer 2010 Express version of Visual Studio with ASP.NET Web API Beta installed.

First we create a new ASP.NET Empty Web Site and give it a reasonable name:

NewWebSite

Then we add an ASP.NET Folder to hold our Web API implementation. We do this by adding an App_Code folder as follows:

NewAppCodeFolder

Next we add a Web API Controller Class within the App_Code folder using Add New Item.

Note: Make sure the name ends in “Controller” and not “Controller1” or similar.

NewController

The newly created ValuesController illustrates a very basic Web API with support for HTTP GET, POST, PUT, and DELETE.

Note: You may have to fix the namespace so that it doesn’t start with a "dot “.” (this is a bug):

FixNamespace

Let’s leave the default ValuesController for now and instead add a route to the global route table so that we can route messages to the Web API.

To do this, open the file Global.asax in the project. Here we need to add two things:

  1. First we add a couple of import statements for System.Web.Routing and System.Web.Http to get the right name places
  2. Second we add a route entry in the global route table in the Application_Start method

The two edits together look like this:

   1: <%@ Application Language="C#" %>
   2: <%@ Import Namespace="System.Web.Routing" %>
   3: <%@ Import Namespace="System.Web.Http" %>
   4:  
   5: <script runat="server">
   6:  
   7:     void Application_Start(object sender, EventArgs e) 
   8:     {
   9:         RouteTable.Routes.MapHttpRoute(
  10:             name: "DefaultApi",
  11:             routeTemplate: "api/{controller}/{id}",
  12:             defaults: new { id = System.Web.Http.RouteParameter.Optional }
  13:         );
  14:     }

You are now ready to try it out so hit F5 and start it!

To see what is going on you can use your browser to send a request to your controller. Typically you would use JavaScript AJAX calls (see for example the tutorial “Your First ASP.NET Web API”) to invoke the ApiController but for GET you can also just use your browser and point it at the address “api/values” relative to the base address of your Web Site.

For example, if your Web Site is running as

then your values controller will be answering at

In IE the default response will be returned as application/json which IE will ask whether you want to open or save. If you save the result and open it then see the JSON result

  • ["value1","value2"]

Alternatively, if you use the address

then you will see only the first value

  • "value"

That’s it – you now have a Web API running in your Web Site.

Have fun!

Henrik

del.icio.us Tags: ,,,,
Comments (22)

  1. sebastian says:

    Just what i was looking for!

    thanks

  2. vantsuyoshi says:

    Hi,

    is there any issue on creating instance of web api controller?

    so maybe i will call it this way on web form

    var controller=new ValueController();

    var debug=controller.Get(6);

    possible? any performance issue?

  3. sam says:

    Where can we find documentation for ASP.NET Web API? The httpClient documentaion on msdn is way out of date.

  4. jim says:

    what should        RouteTable.Routes.MapHttpRoute(   10:             name: "DefaultApi",   11:             routeTemplate: "api/{controller}/{id}",   12:             defaults: new { id = System.Web.Http.RouteParameter.Optional }   13:         ); look like in vb.net?

  5. Haresh Ambaliya says:

    Hi there,

    I want to know that can I use Web API with asp.net forms authentication? I want to implement membership and pass cookie to authenticate every call.

  6. Venkatesan MCA says:

    nice acticle..

  7. Pauli Østerø says:

    Tried to read the article a few times, but still don't see it… where exactly is the Forms part of Web Forms in here?

  8. Can i define more than one route for api controller with different parameters?

  9. YUU says:

    Henrik:

    Great article!!!. Web API will be a replacemet for web services being used by the UI or are a MVC aproach to a web services?

  10. Infoseeker says:

    Hi,

    I am trying to get data from a HttpResponseMessage in webforms. Can anyone please post a code snippet to achieve the same. For example the MVC WebApi is defined as :-

    public HttpResponseMessage PostAddProducts(Product newProduct)

           {

               List<Product> testProduct = new List<Product>();

               testProduct = _productRep.insert(newProduct);

               HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, testProduct);

               return response;                    

           }

  11. Ala'a Alnajjar says:

    That's wonderful,however I'm not sure how to do a unit testing on the controller since it's within app_code,is that even possible?!

  12. Jim says:

    I'm getting a System.Web.Routing.RouteCollection does not contain a definition for 'MapHttpRoute' and the best method overload … has some invalid arguments. Am I missing something?

  13. Mike says:

    Could Web API be used to return HTML as well?

  14. Erick Haryono says:

    for the extension to work, need to add System.Web.Http.WebHost

  15. Darrell says:

    i know its been asked, and i would like to know too.  what should        RouteTable.Routes.MapHttpRoute(   10:             name: "DefaultApi",   11:             routeTemplate: "api/{controller}/{id}",   12:             defaults: new { id = System.Web.Http.RouteParameter.Optional }   13:         ); look like in vb.net?

  16. Duncan Jack says:

    Concise and to the point. Thank you, Henrik.

  17. ss says:

    if has not got this calss what should i do??????????????????

  18. bowman2000 says:

    This looks good.  Can I do this to a framework 3.5 website or web project?

  19. Rakesh says:

    Short and sweet …Great

  20. Cj says:

    Great.. Exactly what I wanted.Are there any drawbacks we need to consider when using both of them together.