在 c# 中,我们有 try & catch 块,我们知道如何避免"Attempted to divide by zero
但在 WebAPi2.0 中,我如何限制用户不输入1/0 或 -1/0
public IHttpActionResult div(int a, int b)
{
return Ok(a / b);
}
在 c# 中,我们有 try & catch 块,我们知道如何避免"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;
}
}