DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on • Updated on

API Methods in ASP.NET Core Web API

ASP.NET Core Web API provides various methods to handle HTTP requests and build RESTful APIs. Some commonly used API methods in ASP.NET Core Web API include:

  1. GET: Used to retrieve data from the server. Typically used when reading or fetching resources. For example:
[HttpGet]
public IActionResult Get()
{
    // Retrieve and return data
    return Ok(data);
}
Enter fullscreen mode Exit fullscreen mode
  1. POST: Used to send data to the server to create a new resource. Typically used for creating new records or performing operations that cause side effects. For example:
[HttpPost]
public IActionResult Post([FromBody] MyModel model)
{
    // Create a new resource using the provided data
    // Return created resource or appropriate response
    return Created(newResourceUri, createdResource);
}
Enter fullscreen mode Exit fullscreen mode
  1. PUT: Used to update an existing resource on the server. Typically used to update entire resource properties. For example:
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] MyModel model)
{
    // Find the resource with the specified ID and update its properties
    // Return the updated resource or appropriate response
    return Ok(updatedResource);
}
Enter fullscreen mode Exit fullscreen mode
  1. PATCH: Used to partially update an existing resource on the server. Typically used to update specific properties of a resource. For example:
[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody] JsonPatchDocument<MyModel> patchDocument)
{
    // Find the resource with the specified ID and apply the patch document to update its properties
    // Return the updated resource or appropriate response
    return Ok(updatedResource);
}
Enter fullscreen mode Exit fullscreen mode
  1. DELETE: Used to delete an existing resource on the server. Typically used to remove a resource. For example:
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
    // Find the resource with the specified ID and delete it
    // Return appropriate response
    return NoContent();
}
Enter fullscreen mode Exit fullscreen mode

These methods are commonly used in ASP.NET Core Web API controllers to handle different types of HTTP requests. They can be decorated with various attributes and configured to accept and return different data formats, such as JSON or XML.

Top comments (0)