How to write Division operation in WebApi2.0

77 Views Asked by At

In c# we have try & catch block we know how to avoid "Attempted to divide by zero But in WebAPi2.0 how can i Restricts user not Enter 1/0 Or -1/0

 public IHttpActionResult div(int a, int b)
        {
            return Ok(a / b);
        }
1

There are 1 best solutions below

0
On BEST ANSWER

You handle this the exact same way. Web Api is only one way of handle communication. The C# logic remains the same.

This is an example of how to do it using DI

public class DivisionController: ApiController
{
    private readonly ICalcService _calcService;

    public DivisionController(ICalcService calcService)
    {
        _calcService = calcService;
    }

    [HttpGet]     
    public IHttpActionResult div(int a, int b)
    {
        return Ok(_calcService.Divide(a,b));
    }
}


public class CalcService: ICalcService
{
    public decimal Divide(int a, int b)
    {
        if(b == 0)
        {
            //handle what to do if it's zero division, perhaps throw exception
            return 0;
        }

        return a / b;
    }
}