create rest api calculator in csharp

Here's an example of how to create a REST API calculator using C# and ASP.NET Web API:

  1. First, create a new ASP.NET Web API project in Visual Studio.
  2. Add a new controller called "CalculatorController" and define two action methods: Add and Subtract.
  3. In the Add and Subtract action methods, use the HttpPost attribute to specify that the methods should only respond to POST requests. Also, add the [FromBody] attribute to indicate that the parameters will be passed in the request body.
  4. Perform the desired calculation and return the result as a response using the Ok method of the controller.

Here's an example of what the code might look like:

main.cs
[Route("api/calculator")]
public class CalculatorController : ApiController
{
    [HttpPost]
    [Route("add")]
    public IHttpActionResult Add([FromBody] CalculationModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var result = model.Number1 + model.Number2;
        return Ok(result);
    }

    [HttpPost]
    [Route("subtract")]
    public IHttpActionResult Subtract([FromBody] CalculationModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var result = model.Number1 - model.Number2;
        return Ok(result);
    }
}

public class CalculationModel
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
}
780 chars
36 lines

In this example, we defined a route for the controller and two additional routes for the Add and Subtract methods. We also defined a model for the two numbers that will be passed in the request body.

To test the API, you can use a tool like Postman to send a POST request to the appropriate route with the numbers as parameters in the request body.

gistlibby LogSnag