Web API  

ASP.NET Web API Cheatsheet – Complete Guide in Simple Language

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?

  • Definition: Web API is a framework for building RESTful services using HTTP.
  • Key Point: It is part of ASP.NET and supports both MVC-style routing and attribute routing.

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

  • Definition: Web API can return data in JSON or XML based on the client's request.
  • Key Point: Set Accept header in the request (application/json or application/xml).

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)

  • Definition: Secure APIs using tokens like JWT.
  • Key Point: In real-world projects, always protect APIs using authentication and authorization.

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)

  • Definition: Use Swagger to auto-generate API documentation.
  • Key Point: Install the Swashbuckle NuGet package and enable it to test APIs via browser.

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

  • Definition: Limits the number of requests a user/client can make in a period.
  • Key Point: Not built-in by default in classic Web API. You can use message handlers or third-party packages like WebApiThrottle.

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

  • Definition: You can use frameworks like NLog, Serilog, or log4net to log information from your Web API.
  • Key Point: Log errors, warnings, and user actions for debugging and audit purposes.

26. API Security Basics

Definition: Protect APIs using techniques like.

  • HTTPS only
  • Token-based authentication (JWT)
  • Role-based access control
  • API keys

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)

  • Definition: Use JWT (JSON Web Tokens) to authenticate API clients.
  • Key Point: JWT tokens are stateless, compact, and ideal for securing APIs. Use middleware or filters to validate.

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

  • Definition: Log complete HTTP request and response lifecycle for audit/debugging.
  • Key Point: Use DelegatingHandler or middleware. Avoid logging sensitive data (like passwords or tokens).

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

  • Definition: Force all incoming API requests to use HTTPS instead of HTTP.
  • Implementation: ASP.NET Web API does not support [RequireHttps] natively like MVC. To enforce HTTPS, use a custom DelegatingHandler or configure it at the IIS/hosting level.

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

  • Definition: Used for uploading files, images, or form data using HTTP POST.
  • Key Point: Manually parse MultipartContent and always validate file type/size.

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

  • Definition: Build a unified interface over multiple APIs, usually done using API gateways like Ocelot.
  • Key Point: Useful in microservices architecture to reduce client complexity.

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

  • Definition: Use Postman, Swagger UI, or REST Client in VS Code to test your APIs.
  • Key Point: Always test edge cases, invalid inputs, and unauthorized access.

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

  • Definition: APIs should be deployed with proper versioning, environment configs, HTTPS, and monitoring.
  • Key Point: Use CI/CD pipelines, set environment variables, and add observability (logs, health checks, alerts).

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)

  • Definition: Browsers send OPTIONS requests before certain CORS requests to check if they are allowed.
  • Key Point: Ensure Web API correctly handles the OPTIONS method for cross-origin calls, especially with authentication.

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

  • Definition: Track who did what, when, and where for security/compliance.
  • Key Point: Log critical changes (data updates/deletes), with user and IP info. Essential in finance/healthcare APIs.

50. IP Whitelisting

  • Definition: Only allow access to the API from approved IP addresses.
  • Key Point: Handled via reverse proxies (e.g., Nginx, IIS), but you can add middleware or custom handlers too.

51. Rate Limiting via Custom Throttling

  • Definition: Restrict how many requests a user or IP can make within a time window.
  • Key Point: Build your own or use packages like WebApiThrottle. Protects against brute force and DoS attacks.

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

  • Definition: Versioning, deprecation notices, sunsetting old endpoints, and backward compatibility.
  • Key Point: Plan versioning before you go live. Always give clients time to migrate.

54. Localization / Globalization

  • Definition: Return API messages or formats based on the user’s locale/culture.
  • Key Point: Support multilingual clients (e.g., date/time/currency formats).

55. OpenAPI Extensions and Code Generation

  • Definition: Generate client SDKs (C#, TypeScript, etc.) using OpenAPI (Swagger) spec.
  • Key Point: Reduces front-end/back-end mismatch. Improves API adoption.

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

  • Definition: These tools provide central control over versioning, throttling, monitoring, authentication, and analytics.
  • Key Point: Vital for large-scale APIs in production. Integrates well with cloud CI/CD.

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

  • Definition: Though Web API is REST-based, you can pair it with SignalR for real-time features.
  • Key Point: Use Web API for CRUD and SignalR for notifications/updates in real time.

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

  • Definition: Separate read (query) and write (command) APIs for better scalability and clarity.
  • Key Point: Use command handlers and query handlers separately. Common in enterprise APIs.

60. Soft Deletes and Archival Endpoints

  • Definition: Don’t delete records from the DB. Mark them inactive and hide from regular queries.
  • Key Point: APIs should offer GET /deleted, GET /archived, or restore endpoints for auditability.