Sdílet prostřednictvím


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: asp.net,web,mvc,webapi,rest

Comments

  • Anonymous
    February 23, 2012
    Just what i was looking for! thanks

  • Anonymous
    February 24, 2012
    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?

  • Anonymous
    February 29, 2012
    Where can we find documentation for ASP.NET Web API? The httpClient documentaion on msdn is way out of date.

  • Anonymous
    February 29, 2012
    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?

  • Anonymous
    March 06, 2012
    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.

  • Anonymous
    March 06, 2012
    good

  • Anonymous
    March 06, 2012
    nice acticle..

  • Anonymous
    March 07, 2012
    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?

  • Anonymous
    March 11, 2012
    Can i define more than one route for api controller with different parameters?

  • Anonymous
    March 16, 2012
    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?

  • Anonymous
    July 30, 2012
    tnx

  • Anonymous
    August 02, 2012
    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;                            }

  • Anonymous
    August 26, 2012
    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?!

  • Anonymous
    September 27, 2012
    The comment has been removed

  • Anonymous
    October 08, 2012
    Could Web API be used to return HTML as well?

  • Anonymous
    October 25, 2012
    for the extension to work, need to add System.Web.Http.WebHost

  • Anonymous
    October 27, 2012
    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?

  • Anonymous
    April 06, 2013
    Concise and to the point. Thank you, Henrik.

  • Anonymous
    November 02, 2013
    if has not got this calss what should i do??????????????????

  • Anonymous
    February 17, 2014
    This looks good.  Can I do this to a framework 3.5 website or web project?

  • Anonymous
    September 23, 2014
    Short and sweet ...Great

  • Anonymous
    November 16, 2014
    Great.. Exactly what I wanted.Are there any drawbacks we need to consider when using both of them together.