Overview
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Framework. Understanding Web API is crucial for developers because it allows them to create services that can be consumed by various clients in a platform-agnostic way, making it a key component in modern web development.
Key Concepts
- RESTful Principles: Web API is designed to support RESTful services which use HTTP requests to perform CRUD operations.
- Routing: Web API uses routing to map incoming HTTP requests to specific controller actions.
- Content Negotiation: It supports content negotiation, which allows the service to provide responses in a variety of formats (e.g., JSON, XML) according to client requests.
Common Interview Questions
Basic Level
- What is ASP.NET Web API and why is it used?
- How do you create a basic Web API controller in ASP.NET?
Intermediate Level
- Explain how routing works in ASP.NET Web API.
Advanced Level
- Discuss the strategies for securing a Web API.
Detailed Answers
1. What is ASP.NET Web API and why is it used?
Answer:
ASP.NET Web API is a framework that simplifies the process of building HTTP services for a wide range of clients, including web browsers and mobile apps. It is used for creating RESTful services, which are based on HTTP and can easily be consumed by any client that understands HTTP. This makes it an essential tool for developing modern web applications that require a backend service to perform CRUD operations (Create, Read, Update, Delete) over HTTP.
Key Points:
- Enables building services that can be accessed from various clients.
- Supports RESTful service architecture.
- Utilizes HTTP as its application protocol.
Example:
using System.Web.Http;
public class ProductsController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "Product1", "Product2" };
}
public string Get(int id)
{
return "Product" + id;
}
}
2. How do you create a basic Web API controller in ASP.NET?
Answer:
To create a basic Web API controller in ASP.NET, you need to derive your controller class from the ApiController
class. This class provides various methods that respond to HTTP verbs (GET, POST, PUT, DELETE).
Key Points:
- Inherit from ApiController
.
- Implement action methods to respond to HTTP requests.
- Use attribute routing or convention-based routing to map requests to actions.
Example:
using System.Collections.Generic;
using System.Web.Http;
public class UsersController : ApiController
{
private static List<string> users = new List<string> { "Alice", "Bob", "Charlie" };
// GET api/users
public IEnumerable<string> Get()
{
return users;
}
// GET api/users/5
public string Get(int id)
{
if (id < users.Count)
{
return users[id];
}
return "Not Found";
}
}
3. Explain how routing works in ASP.NET Web API.
Answer:
Routing in ASP.NET Web API is responsible for directing incoming HTTP requests to specific controller actions. It can be achieved through convention-based routing or attribute routing. Convention-based routing defines routes in the WebApiConfig
file, while attribute routing uses attributes on controllers and actions to define routes directly.
Key Points:
- Convention-based routing is defined globally.
- Attribute routing gives more control by allowing routes to be defined directly above controllers and actions.
- Route templates can include parameter placeholders.
Example:
// Convention-based routing example in WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Attribute routing example
[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
[Route("{id:int}")] // Matches GET api/products/5
public string GetProductById(int id)
{
return "product" + id;
}
[Route("")] // Matches GET api/products
public IEnumerable<string> GetAllProducts()
{
return new string[] { "Product1", "Product2" };
}
}
4. Discuss the strategies for securing a Web API.
Answer:
Securing a Web API involves implementing measures to ensure that only authenticated and authorized users can access the API. Strategies include using HTTPS to encrypt data in transit, authenticating users with tokens (e.g., JWT), and authorizing access to resources based on user roles or claims.
Key Points:
- Utilize HTTPS to protect data in transit.
- Implement token-based authentication to manage user sessions securely.
- Use authorization filters or attributes to control access to resources.
Example:
// Example of a controller using authorization
[Authorize]
public class SecureController : ApiController
{
public IHttpActionResult Get()
{
// This action is secure and requires the user to be authenticated
return Ok("Data accessible only to authenticated users.");
}
}
This guide provides a comprehensive understanding of ASP.NET Web API and its role in building RESTful services, highlighting key concepts, common interview questions, and detailed answers with practical examples.