Web API设计决策:更好地将模型作为参数传递给Service方法或使模型服务?

时间:2018-03-20 10:30:29

标签: web-services asp.net-web-api asp.net-web-api2

我正在创建一个调用服务的Web API方法,如下所示:

public class AlertsController : ApiController
{ 

    IAlertsService _alertsService;
    public AlertsController(IAlertsService alertsService)
    {
        _alertsService = alertsService;
    }        

    [HttpPost]
    public IHttpActionResult Save(AlertModel alertModel)
    {
        if (ModelState.IsValid)
        {
            var alert = _alertsService.SaveAlert(alertModel);
            if (alert != null)
            {
                return Ok(alert);
            }
            return InternalServerError();
        }
        return BadRequest();
    }
 }

正如您所看到的,我正在向alertModel传递 SaveAlert 方法。

您认为使用此代码会更好吗?

 public class AlertsController : ApiController
 { 
   IAlertsService _alertsService;
    public AlertsController(IAlertsService alertsService)
    {
        _alertsService = alertsService;
    }


    [HttpPost]
    public IHttpActionResult Save(AlertModel alertModel)
    {
        if (ModelState.IsValid)
        {

          _alertService.Alert = alertModel; // so have the model defined in 
             // service layer
             var alert = _alertsService.SaveAlert();
            if (alert != null)
            {
                return Ok(alert);
            }
            return InternalServerError();
        }
        return BadRequest();
    }
}

其他一些人更喜欢在模型下实现Save方法,所以要有 alertModel.Save(),但我会保持模型为空。 您认为这将是一个更好的解决方案?

谢谢!

1 个答案:

答案 0 :(得分:1)

在服务中定义模型属性不是一个好习惯。如果您的服务包含超过100或1000的模型和方法来保存实体怎么办?因此,您可以更好地在服务方法中传递模型并实现业务逻辑。