在c#中我们有try&捕获块我们知道如何避免"Attempted to divide by zero
,但是在WebApi2.0中,我如何限制用户不输入 1/0或-1/0
public IHttpActionResult div(int a, int b)
{
return Ok(a / b);
}
您以完全相同的方式处理它。Web API只是处理通信的一种方法。C#逻辑保持不变。
这是如何使用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;
}
}