Introduction

ASP.NET Web API is a framework used to build HTTP services in NET. It helps developers create APIs that can be used by different clients like web apps, mobile apps, and desktop apps. These APIs use HTTP methods like GET, POST, PUT, and DELETE to handle data. It is lightweight and flexible, and it supports content negotiation (like returning JSON or XML).

This cheatsheet covers the most important concepts of Web API in a short and clear format, with examples for each topic. This is helpful if you are learning or revising Web API.

1. What is Web API?

2. Creating a Web API Project

// In Visual Studio:
// File > New > Project > ASP.NET Web Application > Web API template

Key Point: A default controller (like ValuesController) is already created in the template.

3. API Controller

Definition: A controller handles HTTP requests in a Web API.

public class ProductsController : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "Product1", "Product2" };
    }
}

Key Point: It should inherit from ApiController (or ControllerBase in .NET Core).

4. Routing

Definition: Routing maps the request URL to a controller and action.

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

Key Point: Web API uses a different routing system than MVC by default.

5. Attribute Routing

Definition: You can define routes using attributes on controller actions.

[Route("api/products/{id}")]
public string GetProduct(int id)
{
    return "Product " + id;
}

Key Point: Enable it using config.MapHttpAttributeRoutes(); in WebApiConfig.

6. HTTP Methods

Definition: Web API supports standard HTTP methods like GET, POST, PUT, and DELETE.

// GET
public string Get() => "data";

// POST
public void Post([FromBody] string value) { }

// PUT
public void Put(int id, [FromBody] string value) { }

// DELETE
public void Delete(int id) { }

Key Point: Method name must start with Get, Post, Put, or Delete.

7. FromBody and FromUri

Definition: They are used to get input data from the request body or URI.

public void Post([FromBody] Product product) { }

public IHttpActionResult Get([FromUri] int id) { }

Key Point: Use [FromBody] for complex types in POST/PUT. [FromUri] is used for simple query parameters.

8. Return Types

Definition: Return types can be plain data, IHttpActionResult, or HttpResponseMessage.

public IHttpActionResult Get()
{
    return Ok("Hello");
}

Key Point: IHttpActionResult gives more control and better testability.

9. Dependency Injection

Definition: Inject services like repositories into controllers.

public class ProductsController : ApiController
{
    private IProductService _service;
    public ProductsController(IProductService service)
    {
        _service = service;
    }
}

Key Point: Use Unity, Autofac, or a built-in DI container in .NET Core.

10. Content Negotiation

11. Model Validation

Definition: Validate input data using [Required], [StringLength], etc.

public class Product
{
    [Required]
    public string Name { get; set; }
}

Key Point: Check ModelState.IsValid in the controller action.

12. Exception Handling

Definition: Handle errors using try-catch, Exception Filters, or global handlers.

[HttpGet]
public IHttpActionResult Get(int id)
{
    try
    {
        var product = GetProductById(id);
        return Ok(product);
    }
    catch (Exception ex)
    {
        return InternalServerError(ex);
    }
}

Key Point: Global filters can be added using GlobalConfiguration.Configuration.Filters.

13. Cross-Origin Requests (CORS)

Definition: Allows your API to be called from a different domain.

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ProductsController : ApiController
{
}

Key Point: Install Microsoft.AspNet.WebApi.Cors NuGet package and enable CORS in WebApiConfig.

14. Token Authentication (Basic)

15. Calling Web API

From jQuery

$.get("api/products", function(data) {
    console.log(data);
});

From C#

HttpClient client = new HttpClient();
var response = await client.GetAsync("http://localhost/api/products");

Key Point: Use HttpClient to call APIs from C# code.

16. Custom Routes

Definition: You can define specific routes for controller actions.

[Route("api/products/search/{name}")]
public IHttpActionResult SearchByName(string name)
{
    // logic
}

Key Point: Useful for actions that don’t follow standard REST routes.

17. Status Codes

Definition: Use proper HTTP status codes (200, 201, 400, 404, 500, etc.)

return StatusCode(HttpStatusCode.Created);
return BadRequest("Invalid data");

Key Point: Follow standard codes for better API client support.

18. Quick Swagger Setup (Overview)

19. API Versioning

Definition: Allows you to manage different versions of your API without breaking existing clients.

[RoutePrefix("api/v1/products")]
public class ProductsV1Controller : ApiController { }

[RoutePrefix("api/v2/products")]
public class ProductsV2Controller : ApiController { }

Key Point: Helps maintain backward compatibility. You can version by route, query string, or header.

20. Action Results (Common IHttpActionResult Methods)

Definition: Returns specific types of responses.

return Ok();                   // 200 OK
return NotFound();             // 404 Not Found
return BadRequest();           // 400 Bad Request
return StatusCode(HttpStatusCode.Created);  // 201 Created
return InternalServerError(); // 500 Internal Server Error

Key Point: Use these for clear and meaningful API responses.

21. Throttling / Rate Limiting

22. Filters (Action Filters, Exception Filters, etc.)

Definition: Used to run code before/after actions globally or per controller/action.

public class LogFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        // logging logic
    }
}

Key Point: Useful for cross-cutting concerns like logging, validation, and exception handling.

23. Custom Middleware / Delegating Handlers

Definition: Middleware that processes HTTP requests/responses at a low level.

public class CustomHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Custom logic
        return await base.SendAsync(request, cancellationToken);
    }
}

Key Point: Great for logging, authentication, or modifying requests globally.

24. Async and Await Support

Definition: Web API fully supports async programming for non-blocking I/O.

public async Task<IHttpActionResult> Get()
{
    var data = await _service.GetDataAsync();
    return Ok(data);
}

Key Point: Always use async for I/O-bound operations (database, API calls) to improve performance.

25. Logging

26. API Security Basics

Definition: Protect APIs using techniques like.

Key Point: Security is critical. Always validate inputs, sanitize outputs, and follow secure coding practices.

27. Full Swagger/OpenAPI Integration (Advanced)

Definition: Swagger (via the Swashbuckle package) auto-generates UI documentation for your Web API.

// Install-Package Swashbuckle
// In WebApiConfig.cs
config.EnableSwagger(c => {
    c.SingleApiVersion("v1", "Product API");
}).EnableSwaggerUi();

Key Point: Allows easy testing and visual exploration of endpoints. Makes APIs self-explanatory.

28. Authentication and Authorization

Definition: Use filters or middleware to restrict access based on roles, claims, or tokens.

[Authorize(Roles = "Admin")]
public class AdminController : ApiController { }

Key Point: Combine the Authorize attribute with JWT Bearer or OAuth 2.0 for secure APIs.

29. Token-Based Authentication (JWT)

30. Role-Based and Claims-Based Access

Definition: Control access using user roles or custom claims inside tokens.

[Authorize(Roles = "Manager")]
public class ReportsController : ApiController { }

Key Point: Fine-grained control over who can access what.

31. Global Error Handling

Definition: Use ExceptionHandler or ExceptionLogger to catch and log unhandled exceptions globally.

public class GlobalExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        context.Result = new InternalServerErrorResult(context.Request);
    }
}

Key Point: Avoid leaking stack traces. Always return user-friendly error messages.

32. Request and Response Logging

33. API Response Wrapping

Definition: Standardize all responses in a consistent format.

{
  "status": "success",
  "data": {...},
  "message": null
}

Key Point: Improves client-side error handling and debugging.

34. Custom Model Binders

Definition: Used to bind request data to complex objects when default binding fails.

public class CustomBinder : IModelBinder { ... }

Key Point: Useful for binding non-standard formats or when data comes from mixed sources.

35. Caching Responses

Definition: Use OutputCache, custom headers, or memory cache to store repeated results.

[OutputCache(Duration = 60, VaryByParam = "none")]
public IHttpActionResult Get() { ... }

Key Point: Improves performance for read-heavy APIs. Avoid caching sensitive or changing data.

36. Media Formatters

Definition: Customize how data is serialized (e.g., JSON, XML, CSV) using formatters.

config.Formatters.JsonFormatter.SerializerSettings.Formatting = 
    Formatting.Indented;

Key Point: Remove XML formatter if you want only JSON: config.Formatters.Remove(config.Formatters.XmlFormatter);

37. Enforcing HTTPS in ASP.NET Web API

Example (Custom DelegatingHandler)

public class RequireHttpsHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            return Task.FromResult(
                request.CreateResponse(HttpStatusCode.Forbidden, "HTTPS is required")
            );
        }
        return base.SendAsync(request, cancellationToken);
    }
}

Register the handler in WebApiConfig.cs.

config.MessageHandlers.Add(new RequireHttpsHandler());

Key Point: There is no built-in [RequireHttps] in Web API. Use a custom handler or enforce HTTPS at the IIS/server level. Never expose APIs handling sensitive data over plain HTTP.

38. Handling Multipart Form Data

39. Using HTTP PATCH for Partial Updates

Definition: Use PATCH when only some fields need to be updated.

[HttpPatch]
public IHttpActionResult Patch(int id, JsonPatchDocument<Product> patchDoc) { ... }

Key Point: Install support via Microsoft.AspNet.WebApi.JsonPatch (or write custom logic).

40. API Gateways and Aggregation

41. Using HATEOAS (Hypermedia as the Engine of Application State)

Definition: Add navigational links in your API responses.

{
  "id": 1,
  "name": "Item",
  "links": [
    { "rel": "self", "href": "/api/items/1" },
    { "rel": "delete", "href": "/api/items/1" }
  ]
}

Key Point: Improves discoverability and client navigation.

42. API Testing Tools

43. Handling Circular References in JSON

Definition: Avoid JSON serialization errors caused by self-referencing objects.

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
    ReferenceLoopHandling.Ignore;

Key Point: Avoid exposing entire object graphs to the client.

44. API Deployment Considerations

45. Message Handlers (Custom HTTP Pipeline Processing)

Definition: DelegatingHandler lets you intercept HTTP requests/responses globally.

public class LoggingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Logging logic
        return await base.SendAsync(request, cancellationToken);
    }
}

Key Point: Ideal for custom authentication, logging, headers, correlation IDs, etc.

46. Conditional Requests (ETag / If-Modified-Since)

Definition: Improve performance by letting the client cache responses and check if the data has changed.

var response = Request.CreateResponse(HttpStatusCode.OK, product);
response.Headers.ETag = new EntityTagHeaderValue("\"12345\"");

Key Point: Avoid sending full data again if nothing has changed. Useful for read-heavy APIs.

47. HTTP OPTIONS and Preflight Requests (CORS Handling)

48. Health Checks / Readiness Probes

Definition: Custom endpoints to report API health to load balancers or monitoring tools.

[Route("api/health")]
public IHttpActionResult HealthCheck() => Ok("Healthy");

Key Point: Needed for Kubernetes, Azure App Services, or any auto-scaling infra.

49. API Auditing

50. IP Whitelisting

51. Rate Limiting via Custom Throttling

52. Response Compression (GZip)

Definition: Reduce payload size using compression (e.g., GZip).

config.MessageHandlers.Add(
    new ServerCompressionHandler(
        new GZipCompressor(),
        new DeflateCompressor()
    )
);

Key Point: Improves performance, especially for large responses.

53. API Lifecycle Management

54. Localization / Globalization

55. OpenAPI Extensions and Code Generation

56. Using API Management Tools (Azure API Management, Kong, etc.)

57. WebSockets or SignalR Integration (Not Typical but Possible)

58. Using Filters for Response Shaping (Fields Selection)

Definition: Allow clients to choose only specific fields in response to reduce payload.

GET /api/products?fields=name,price

Key Point: Improves performance on mobile clients or limited-bandwidth situations.

59. CQRS (Command Query Responsibility Segregation) in API Design

60. Soft Deletes and Archival Endpoints