DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • ASP.NET Web API: Benefits and Why to Choose It
  • Revolutionizing Content Management
  • Building a Microservices API Gateway With YARP in ASP.NET Core Web API
  • Popular APIs for the Internet of Things (IoT) Systems

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Ensuring Configuration Consistency Across Global Data Centers
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Web API in ASP.NET Web Forms Application

Web API in ASP.NET Web Forms Application

With the release of ASP.NET MVC 4 one of the exciting features packed in the release was ASP.NET Web API.

By 
Lohith Nagaraj user avatar
Lohith Nagaraj
·
May. 24, 13 · News
Likes (0)
Comment
Save
Tweet
Share
51.0K Views

Join the DZone community and get the full member experience.

Join For Free


with the release of asp.net mvc 4 one of the exciting features packed in the release was asp.net web api. in a nutshell, asp.net web api is a new framework for creating http services that can reach a broad range of clients including browsers and mobile devices. asp.net web api is also an ideal platform for building restful services.

microsoft shipped “asp.net and web tools 2012.2” update sometime in february 2013. this included updated asp.net mvc templates, asp.net web api, signalr and friendly urls. so if you take the latest you get all the latest bits asp.net has to offer so far. rest of this post assumes that you have installed the 2012.2 bits. i assume you know the web api fundamentals like api controller,  action and route configuration as i wont get into discussing those.

in this post, we will see how web api can be created in a web form application or project. i will be using visual studio express 2012 for web as my ide for this post.

create asp.net web form project:

to start out with, create a empty “asp.net empty web application” or “asp.net web forms application”. both of these templates are web forms based. so doesn’t matter which one you choose. for the sake of the demo i will choose asp.net empty web application. fire up a visual studio express 2012 for web, file > new project > asp.net empty web application and give a name to the project.

image fig 1: new project dialog

visual studio will create the project and you should have the infrastructure ready. and here is how the solution will look like:

image
fig 2: solution explorer

adding a web api controller:

since web api is kind of api we are building lets bring in some best practice here. it is good to have a folder created with the name “api” and store all your web api controllers here. with the latest release of asp.net, you can create controllers in any folder you like. so go ahead and create a new folder and name it api. here is how the solution explorer will look like:

image
fig 3: api folder

now lets add a web api controller. right click on api folder, select add > new item. you will find a new item template called “web api controller class”. select web api controller class item. note that visual studio names the class as valuescontroller1.cs – you can rename it to valuescontroller. make the changes and click add.

image
fig 4: adding web api controller class

here is the glimpse of the code inside valuescontroller class provided by default:

image
fig 5: values controller class

there is one magic visual studio does under the hood when you add a web api controller class. it adds the following packages which is required for making the web api work:

  • microsoft.aspnet.webapi
  • microsoft.aspnet.webapi.client
  • microsoft.aspnet.webapi.core
  • microsoft.aspnet.webapi.webhost
  • microsoft.net.http
  • newtonsoft.json

you can see that there is a packages.config file added to the solution and it is used by nuget package manager to keep track of the packages. the above packages make it possible for web api to be hosted within the web forms application or project. so, is this all to make the web api run – well not yet. web api works with the routes and we have not yet configured the routing engine to grab the request and see if it is web api request. lets do that in next section.

setting up web api routes:

one thing you will notice in the solution is – it does not contain a global.asax file. well that’s why the name of the template “asp.net empty web application” its literally empty and you need to add things needed manually. so first lets go ahead and add a global.asax. right click on the project, select add > new item > global application class. you will get the blank global.asax i.e. the class will have all the event handler added up but empty. the event handler which is of importance for us is application_start. lets now configure the http routing. as a best practice create a new folder called app_start at the root of the project. add a new class, call it webapiconfig.cs and make it a static class. idea behind naming the folder as app_start is that, codes in this folder are the first to be called or executed when the app starts. so here is how the solution explorer looks like now:

image
fig 6: solution explorer

now add the following code to webapiconfig.cs. we are creating a static method called register and it will register the http routes for the application:


public static void register(httpconfiguration config)
{
    config.routes.maphttproute(
        name: "defaultapi",
        routetemplate: "api/{controller}/{id}",
        defaults: new { id = routeparameter.optional }
    );
}



listing 1: webapiconfig register method

what we are doing in register method is:

  • get the httpconfiguration object
  • use the routes table to configure routes
  • map a http route to our api by providing a pattern
  • default pattern is to look for “api/{controller}/{id} – where {id} is optional

here is the complete code of webapiconfig.cs file:


using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.http;

namespace webapiinwebforms.app_start
{
    public static class webapiconfig
    {
        public static void register(httpconfiguration config)
        {
            config.routes.maphttproute(
                name: "defaultapi",
                routetemplate: "api/{controller}/{id}",
                defaults: new { id = routeparameter.optional }
            );
        }
    }
}




listing 2: webapiconfig class

now, this is just a definition but where do we actually call it. remember we added a global.asax file – we will call the register method from the application_start event handler. here is the code to do that:


protected void application_start(object sender, eventargs e)
{
   webapiconfig.register(globalconfiguration.configuration);
}




listing 3: global.asax application_start event handler

and we have a web api created in web forms project now. next lets see how to test it out.

testing web api:

at this moment if you build and run the project, browser may show you 403 and that is expected as we do not have an default.aspx or index.html. don’t worry as we are interested in testing the api controller. remember the default patterns we set up for api routes – our web api is available at a url “ http://localhost:<port>/api/values ”. so type the url and hit enter. ie will show you the response as a json value. this is because ie always sends the accept header as application.json and web api server implementation will respect the content negotiation and send the appropriate data type to the client.

image
fig 7: testing api controller in ie

here is the same response when seen from firefox:

image
fig 8: testing api controller in firefox

summary:

this was a post intended to show case the fact that web api are not meant only for asp.net mvc project types but it can be hosted even in asp.net web forms project too. thanks to the tooling, visual studio does all the magic under the hoods when you add a item template of type “web api controller class”. we saw how easy it is to set up a api controller and test it.  hope this gives you a jump start on creating web api in web forms project. do let me know if you have any feedback on this article. it will help me better myself.

till next time – happy coding. code with passion, decode with patience.



Web API Web Service mobile app Form (document) ASP.NET Web Forms ASP.NET API

Published at DZone with permission of , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • ASP.NET Web API: Benefits and Why to Choose It
  • Revolutionizing Content Management
  • Building a Microservices API Gateway With YARP in ASP.NET Core Web API
  • Popular APIs for the Internet of Things (IoT) Systems

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!