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:
- 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);
}
- 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);
}
- 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);
}
- 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);
}
- 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();
}
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)