Previous Middleware in ASP.NET Core Filters in ASP.NET Core Next

HTTP Verbs in ASP.NET Core

HTTP Verbs in ASP.NET Core

HTTP verbs (also known as HTTP methods) originated with the HTTP protocol in the early 1990s as part of the foundational architecture of the World Wide Web. Defined by the HTTP/1.0 and later HTTP/1.1 specifications, these verbs were designed to standardize how clients interact with resources on a server. Over time, they became central to RESTful architecture, which emphasizes stateless communication and resource-based design.

In ASP.NET Core Web API, HTTP verbs are mapped to controller actions using attributes like [HttpGet], [HttpPost], and others. This alignment with REST principles allows developers to build clean, scalable, and intuitive APIs that mirror real-world operations—such as retrieving, creating, updating, or deleting data.

Common HTTP Verbs

Verb Purpose Attribute Idempotent Safe Example Method
GET Retrieve data [HttpGet] Yes Yes GetBooks()
POST Create a new resource [HttpPost] No No PostBook(Book book)
PUT Replace an existing resource [HttpPut] Yes No PutBook(int id, Book book)
PATCH Partially update a resource [HttpPatch] Yes No PatchBook(int id, JsonPatchDocument<Book> patch)
DELETE Remove a resource [HttpDelete] Yes No DeleteBook(int id)

Controller Example

[ApiController]
[Route("api/[controller]")]
public class BooksController : ControllerBase
{
    private static List<string> books = new() { "Clean Code", "Domain-Driven Design" };

    [HttpGet]
    public IEnumerable<string> Get() => books;

    [HttpPost]
    public IActionResult Post([FromBody] string book)
    {
        books.Add(book);
        return CreatedAtAction(nameof(Get), new { id = books.Count - 1 }, book);
    }

    [HttpPut("{id}")]
    public IActionResult Put(int id, [FromBody] string book)
    {
        if (id >= books.Count) return NotFound();
        books[id] = book;
        return NoContent();
    }

    [HttpPatch("{id}")]
    public IActionResult Patch(int id, [FromBody] string bookFragment)
    {
        if (id >= books.Count) return NotFound();
        books[id] = books[id] + " " + bookFragment; // Simple patch logic
        return Ok(books[id]);
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        if (id >= books.Count) return NotFound();
        books.RemoveAt(id);
        return NoContent();
    }
}
  

Precautions When Using HTTP Verbs

  • Validate Input Thoroughly: Always validate incoming data using model validation attributes like [Required], [Range], and custom validators to prevent injection attacks and malformed requests.
  • Use Authorization and Authentication: Protect sensitive operations like POST, PUT, PATCH, and DELETE with proper authentication (e.g., JWT) and role/claims-based authorization.
  • Limit Verb Exposure: Avoid exposing unnecessary endpoints. For example, if your API only supports reading data, don’t include POST, PUT, or DELETE routes.
  • Enforce HTTPS: Always use HTTPS to encrypt data in transit, especially for POST, PUT, and PATCH operations that carry sensitive payloads.
  • Rate Limiting and Throttling : Apply rate limits to prevent abuse of GET or POST endpoints, especially in public APIs.
  • Use Idempotency Where Required: Ensure PUT, PATCH, and DELETE operations are idempotent to avoid unintended side effects from repeated requests.
  • Return Appropriate Status Codes: Always respond with meaningful HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error) to guide client behavior and debugging.
  • Log and Monitor: Log all incoming requests and responses, especially for POST, PUT, and DELETE actions, to aid in auditing and troubleshooting.
  • Use Content-Type Headers: Ensure clients send the correct Content-Type (e.g., application/json) and validate it server-side to prevent parsing errors or security issues.
  • Avoid Overloading Verbs: Don’t mix responsibilities. For example, don’t use GET to perform updates or deletions—this breaks REST principles and can lead to security flaws.

Testing Strategies

  • Swagger UI: Auto-generates interactive API documentation for testing endpoints.
  • Postman: Send HTTP requests with headers, bodies, and tokens for manual testing.
  • curl: Command-line tool for quick HTTP requests. Example: curl -X GET https://localhost:5001/api/books

Best Practices

  • Use [ApiController] to enable automatic model validation and binding.
  • Return appropriate HTTP status codes: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found, etc.
  • Validate input models using [Required], [StringLength], and other data annotations.
  • Use PUT for full updates and PATCH for partial updates.
  • Ensure DELETE operations are protected with proper authorization policies.
  • Use CreatedAtAction or CreatedAtRoute when returning newly created resources.
  • Keep controller actions focused—avoid mixing business logic with request handling.
  • Log incoming requests and responses for auditing and debugging.
  • Use route constraints to validate parameters (e.g., [HttpGet("{id:int}")]).
  • Document your API endpoints using XML comments and Swagger annotations.
Back to Index
Previous Middleware in ASP.NET Core Filters in ASP.NET Core Next
*