Web API 设计决策:最好将模型作为参数传递给服务方法,或者让模型处于服务中



我正在创建一个调用服务的 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(( ,但我会将模型保留为空。您认为什么是更好的解决方案?

谢谢!

服务中定义模型属性不是好的做法。 如果您的服务包含超过 100 或 1000 个用于保存实体的模型和方法,该怎么办? 因此,最好在服务方法中传递模型并实现业务逻辑。

最新更新