Building Web APIs with ASP.NET: A Comprehensive Guide

This guide explores ASP.NET Web APIs, explaining their purpose, advantages (simplicity, scalability, RESTful support), and comparing them to other technologies like WCF. Learn why Web APIs are a popular choice for building modern, interconnected applications and how they facilitate efficient data exchange between systems. The benefits of using a RESTful approach are also discussed.



Top Web API Interview Questions and Answers

What is a Web API?

Question 1: What is a Web API?

A Web API (Application Programming Interface) is a framework for creating HTTP-based services that can be accessed by various clients (web browsers, mobile apps, etc.). These APIs allow different applications to communicate and exchange data. ASP.NET Web API is a popular framework for building these services on the .NET platform.

Why Use Web API?

Question 2: Reasons to Use Web API

Web APIs are preferred for several reasons:

  • HTTP-based: Leverages the widely used HTTP protocol for communication.
  • RESTful Services: Easily creates RESTful services using HTTP verbs (GET, POST, PUT, DELETE).
  • Lightweight: Ideal for devices with limited bandwidth (like smartphones).
  • Flexible Data Formats: Supports JSON and XML responses.
  • OData Support: Can use the Open Data Protocol (OData) for data access.

Web API vs. WCF and RESTful Services

Question 3: Web API and RESTful Services with WCF

Yes, you can create RESTful services using WCF (Windows Communication Foundation), but Web API is often preferred because it's simpler to use, especially for building RESTful services, and better supports the test-driven development (TDD) approach. WCF offers broader capabilities than Web API but requires more configuration.

Question 4: Web API Replacing WCF?

No, Web API doesn't entirely replace WCF. Web API is optimized for HTTP-based services, whereas WCF supports various protocols (HTTP, TCP, MSMQ). Choose Web API for HTTP-only needs; use WCF for more diverse communication protocols.

Question 5: Web API vs. WCF

Key differences between Web API and WCF:

Feature Web API WCF
Protocol Primarily HTTP HTTP, TCP, MSMQ, etc.
Data Format JSON, XML XML (primarily)
Complexity Generally simpler More complex
Use Cases RESTful services, APIs for mobile apps Enterprise-level services, diverse communication needs

Web API Advantages

Question 6: Advantages of Web API

Web API offers several advantages:

  • Content Negotiation: Ability to return data in different formats (JSON, XML).
  • Self-Hosting: Can be hosted in various environments (not just IIS).
  • OData Support: Supports the Open Data Protocol.
  • Filters: Allows filtering of data based on various criteria.
  • Routing: Defines how requests are mapped to controller actions.
  • Model Binding: Automatic mapping of request data to model objects.

Web API vs. MVC

Question 7: Web API vs. MVC

While both are .NET technologies, they serve different purposes:

Feature MVC Web API
Purpose Building web applications with UIs Building HTTP services
Output Views and data Data only (JSON, XML, etc.)
Request Mapping Action methods HTTP verbs (GET, POST, etc.)

Question 8: .NET Framework Support for Web API

.NET Framework 4.0 and later versions support Web API.

Question 9: Web API Return Types

Web API controller actions can return:

  • void: Empty response.
  • HttpResponseMessage: Full control over the HTTP response.
  • IHttpActionResult: A more structured way to return responses.
  • Other Types: Custom types that are serialized into the response body.

Question 10: JSON Serialization Library

Web API uses Newtonsoft.Json (JSON.NET) for JSON serialization.

Question 11: Drawback of "Other Return Types"

A major drawback of using custom types as return values is that you have to manually set HTTP status codes (like 404 Not Found) for error conditions.

Question 12: Web API Routing

Web API routing maps incoming HTTP requests to controller actions. It's similar to MVC routing but uses HTTP verbs to determine the action to be performed.

Question 13: Cross-Language Use of Web API

Yes, ASP.NET Web API can be consumed by applications written in languages other than .NET, as long as those applications can make HTTP requests.

Question 14: SOAP

SOAP (Simple Object Access Protocol) is a messaging protocol for exchanging information over a network. It often uses XML for message formatting and commonly runs over HTTP or other transport mechanisms.

Question 15: Web API with ASP.NET Web Forms

You can use Web API with ASP.NET Web Forms. You create a Web API controller, configure routes, and then use AJAX (e.g., with jQuery) in your Web Forms to call the Web API methods.

Question 16: Restricting HTTP Verbs

You can restrict access to a Web API controller method to specific HTTP verbs (GET, POST, PUT, DELETE) using attributes like [HttpGet], [HttpPost], etc.

Question 17: RESTful Services

REST (Representational State Transfer) is an architectural style for creating web services. Key principles include a stateless client-server architecture, a uniform interface, and the use of standard HTTP methods.

Question 18: Exception Filters

Exception filters in Web API handle uncaught exceptions that occur during a request. They allow you to implement custom error handling logic to provide a more consistent and informative response to the client.

Question 19: TestApi

TestApi is a testing framework for .NET applications. It provides tools for writing automated tests for Web APIs.

Question 20: Returning Views from Web API

No, Web APIs typically don't return views (HTML). They return data (JSON, XML, etc.). If you need to render views, you'd typically use an MVC controller.

Parameter Binding in Web API

Question 21: Parameter Binding in Web API

Parameter binding in Web API automatically maps data from an HTTP request to the parameters of a controller action. The binding mechanism depends on the parameter type:

  • Simple Types: (int, string, DateTime, etc.) Values are obtained from the URI.
  • Complex Types: Values are obtained from the request body (typically JSON).

Global Exception Handling

Question 22: Registering Exception Filters Globally

To register an exception filter globally in Web API, use the following code:

C# Code

GlobalConfiguration.Configuration.Filters.Add(new MyCustomExceptionFilterAttribute());

REST vs. RESTful

Question 23: REST vs. RESTful

REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful refers to an application that adheres to the constraints of the REST architectural style.

Content Negotiation

Question 24: Content Negotiation

Content negotiation allows clients to specify the format (e.g., JSON, XML) they prefer for a response. The server then returns the response in the requested format. The Accept header in the HTTP request is typically used to indicate the preferred format.

Web API Routing

Question 25: Web API Routing Example

Here's how to define a route in Web API:

C# Code

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Media-Type Formatters

Question 26: Media-Type Formatters

Media-type formatters in Web API handle serialization and deserialization of data in different formats (JSON, XML). JsonMediaTypeFormatter and XmlMediaTypeFormatter are examples of formatters.

Error Handling in Web API

Question 27: Error Handling in Web API

Several mechanisms exist for error handling in Web API, including HttpResponseException, HttpError, and exception filters. Exception filters provide a centralized approach to handling exceptions that occur within controller actions.

ASP.NET Web API 2.0 Features

Question 28: New Features in Web API 2.0

Web API 2.0 introduced several enhancements:

  • Attribute Routing: More flexible and expressive route definitions.
  • Owin Support: Integration with the Open Web Interface for .NET (OWIN).
  • CORS (Cross-Origin Resource Sharing): Enables cross-domain requests.
  • External Authentication: Support for integrating with external authentication providers.
  • IHttpActionResult: A more structured way to define action results.
  • OData Support: Built-in support for OData.

Restricting HTTP Verbs

Question 29: Restricting Access to HTTP Verbs

You can restrict access to controller methods to specific HTTP verbs (GET, POST, PUT, DELETE) using attributes like [HttpGet], [HttpPost], etc.

Example: [HttpPost] Attribute

[HttpPost]
public IHttpActionResult MyPostMethod(MyData data) {
  // ... your code ...
}

Authorize Attribute

Question 30: Authorize Attribute

The [Authorize] attribute in Web API restricts access to controller actions to authenticated users. Unauthenticated requests will result in a 401 Unauthorized response.

Passing Multiple Complex Types

Question 31: Passing Multiple Complex Types

You can pass multiple complex types to Web API methods using either an array or a custom class that encapsulates those types.

Basic HTTP Authentication

Question 32: Basic HTTP Authentication

Basic HTTP authentication transmits username and password credentials encoded in the request headers. While simple to implement, it transmits credentials in plain text (using Base64 encoding), so it's not ideal for sensitive data.

Passing ArrayLists in Web API

Question 33: Passing an ArrayList

You can pass an ArrayList to a Web API method by serializing it to JSON (or XML) in the request body. The Web API method would typically accept a parameter of the corresponding type (e.g., a list of objects).

Routing HTTP Requests

Question 34: Routing HTTP Requests to Controller

Web API uses a routing table to map incoming HTTP requests to the appropriate controller actions based on the URI.

Error Handling with HttpError

Question 35: Handling Errors with HttpError

The HttpError class (or HttpResponseException) is used to throw HTTP error responses from Web API controller actions. The `HttpRequestMessage.CreateErrorResponse` method is commonly used to create these responses.

Global Exception Filter Registration (Again)

Question 36: Global Exception Filter Registration

Register exception filters globally to handle exceptions across your entire Web API application. Use `GlobalConfiguration.Configuration.Filters.Add(...)` to register the filter.

Exception Handling in Web API

Question 37: Exception Handling in Web API

Various techniques are used for exception handling in Web API, including using HttpResponseException, `HttpError`, and custom exception filters to provide consistent and informative error responses to clients.

Web API Versioning

Question 38: Web API Versioning

Web API versioning allows you to maintain multiple versions of your API while supporting different clients using different versions.

Question 39: Web API Versioning Methods

Common Web API versioning techniques include URI versioning, query string parameter versioning, header versioning, and content negotiation versioning.

Web API vs. WCF (Again)

Question 40: Advantages of Web API over WCF

Web API is generally preferred over WCF for building RESTful services because it's simpler, more lightweight (due to its HTTP-only focus), and requires less configuration.

MVC vs. Web API (Again)

Question 41: MVC vs. Web API

MVC is designed for building web applications with UIs, while Web API is specifically for building HTTP services that can be consumed by various clients.

Web API Clients

Question 42: Web API Clients

Any client capable of making HTTP requests (GET, POST, PUT, DELETE, etc.) can consume a Web API. This includes web browsers, mobile apps, and other backend systems.

HTTP Methods in Web API

Question 43: HTTP Methods

Web API utilizes standard HTTP methods:

  • GET: Retrieves data.
  • POST: Creates a new resource.
  • PUT: Updates an existing resource.
  • DELETE: Deletes a resource.
  • HEAD: Similar to GET but only returns headers.
  • OPTIONS: Describes communication options.
  • CONNECT: Establishes a tunnel.
  • TRACE: Performs a message loop-back test.

HTTP Status Codes

Question 44: HTTP Status Codes

HTTP status codes are three-digit numbers that indicate the result of an HTTP request. The first digit categorizes the response:

  • 1xx (Informational): The request was received and is being processed.
  • 2xx (Success): The request was successfully processed.
  • 3xx (Redirection): Further action is required to complete the request.
  • 4xx (Client Error): The request had a problem (e.g., bad request, unauthorized).
  • 5xx (Server Error): The server encountered an error.

Question 45: Common HTTP Status Codes

Some commonly encountered HTTP status codes:

  • 200 OK: Successful request.
  • 201 Created: Resource successfully created.
  • 400 Bad Request: Client sent a malformed request.
  • 401 Unauthorized: Client needs to authenticate.
  • 404 Not Found: Resource not found on the server.
  • 500 Internal Server Error: Server encountered an unexpected error.

Internet Media Types (MIME Types)

Question 46: Internet Media Types

Internet media types (MIME types) identify the type of data being sent (e.g., text/html, application/json). They're used in HTTP headers to tell the client how to handle the received data.

XML vs. JSON

Question 47: XML vs. JSON

Both XML and JSON are used for data interchange, but:

Feature XML JSON
Structure Uses tags (markup language) Uses key-value pairs (JavaScript-like notation)
Verbosity More verbose More concise
Parsing Requires more processing Generally easier to parse
Readability Can be less readable for large datasets Generally more readable

Question 48: ASP.NET Web API Introduction

ASP.NET Web API was first introduced in .NET Framework 4. Later .NET versions also support it.

WCF vs. MVC vs. Web API

Question 49: WCF vs. MVC vs. Web API

These are all .NET technologies, but they serve different purposes:

Technology Purpose Data Format Communication
WCF (Windows Communication Foundation) Building service-oriented applications (supports various protocols) Typically XML Variety of protocols (HTTP, TCP, etc.)
MVC (Model-View-Controller) Building web applications with user interfaces HTML, JSON HTTP
Web API Building HTTP-based services (RESTful APIs) JSON, XML HTTP

Web API Unit Testing

Question 50: Unit Testing Web API

You can unit test Web API controllers using tools like Fiddler or dedicated testing frameworks like NUnit or xUnit. These tools allow you to send HTTP requests to your API and assert the responses.

Returning JSON Regardless of Accept Header

Question 51: Forcing JSON Responses

To ensure a Web API always returns JSON, remove the XML formatter from the configuration in your WebApiConfig.cs file:

C# Code

config.Formatters.Remove(config.Formatters.XmlFormatter);

Controller vs. ApiController

Question 52: Controller vs. ApiController

In ASP.NET:

  • Controller: Used for MVC applications; returns views (HTML).
  • ApiController: Used for Web API; returns data (JSON, XML).