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.
First we create a new ASP.NET Empty Web Site and give it a reasonable name:
Then we add an ASP.NET Folder to hold our Web API implementation. We do this by adding an App_Code folder as follows:
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.
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):
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:
- First we add a couple of import statements for System.Web.Routing and System.Web.Http to get the right name places
- Second we add a route entry in the global route table in the Application_Start method
The two edits together look like this:
You are now ready to try it out so hit F5 and start it!
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
Alternatively, if you use the address
then you will see only the first value
That’s it – you now have a Web API running in your Web Site.