Wednesday, April 19, 2023

What are the different types of HTTP requests and how do you handle them in a .NET Core Web API?

There are several types of HTTP requests that a client can send to a web API, including:

  1. GET: Retrieves information or data from the server.
  2. POST: Submits data to the server to create a new resource.
  3. PUT: Updates an existing resource on the server.
  4. DELETE: Removes a resource from the server.
  5. PATCH: Partially updates a resource on the server.


In a .NET Core Web API, you can handle these HTTP requests by defining controller actions that correspond to each request type. For example, to handle a GET request, you would define a controller action that returns the requested data. To handle a POST request, you would define a controller action that accepts the data and creates a new resource.

You can use the HTTP attributes in ASP.NET Core to specify the HTTP method that the controller action handles. For example, to handle a GET request, you would decorate the action with the [HttpGet] attribute, and to handle a POST request, you would decorate the action with the [HttpPost] attribute.

Here's an example of handling a GET request in a .NET Core Web API:

[HttpGet]
public IActionResult Get()
{
    // Get the data from the server
    var data = GetData();

    // Return the data as a JSON response
    return Json(data);
}
 

And here's an example of handling a POST request:

[HttpPost]
public IActionResult Post([FromBody] MyModel model)
{
    // Save the new resource to the server
    SaveData(model);

    // Return a success response
    return Ok();
}


In these examples, GetData() and SaveData() are placeholder methods that handle the actual data retrieval and storage. The Json() and Ok() methods return a JSON response and a 200 OK response, respectively.

 

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.