0

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);
        }
  • The exakt same way. Web Api is only one way of handle communication. The C# logic remains the same. Create a method/class that handles the calculation which you call from your controller. – Marcus Höglund Sep 08 '17 at 06:40
  • Could u plz Reffere any sample code –  Sep 08 '17 at 06:51

1 Answers1

0

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;
    }
}
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69