0

我正在使用带有实体框架和 Backbone.js 的 ASP.NET Web API

我正在开发一个更新模块,允许用户更新他的 XYZ。

现在,更新时可能会出现3种情况

  • 成功
  • 失败的
  • 未找到

所以我决定使用这个名为

enum UpdateStatus
{
    Success = 1,
    Failed = 0,
    NotFound = 2
}

所以这就是我的方法的样子

public UpdateStatus UpdateXYZ(Model model)
{
    var data = _repo.Table.where(m => m.id == model.id);
    if(data.count == 0)
    {
        return UpdateStatus.NotFound;
    }

    try
    {
        // update here
        return UpdateStatus.Sucess; 
    }
    catch
    {
        // log errors
        return UpdateStatus.Failed;
    }
}

然后稍后在服务层中,我将向我的 web api 操作返回相同的值。然后在 web api 操作中,我会有类似...

public HttpResponseMessage Put(Details details)
{
    if (ModelState.IsValid)
    {
        //The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent.
        //return new HttpResponseMessage(HttpStatusCode.ResetContent);
        UpdateStatus = _magicService.UpdateXYZ(details);
        if (UpdateStatus.Success)
        {
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
        else if(UpdateStatus.NotFound)
        {
            return new HttpResponseMessage(HttpStatusCode.Gone);
        }
        return new HttpResponseMessage(HttpStatusCode.Conflict);
    }
    else
    {
        string messages = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage + " - " + (x.Exception == null ? "" : x.Exception.Message)));
        return Request.CreateResponse<string>(HttpStatusCode.BadRequest, messages.ToString());
    } 

}   

我已经在我的 repo 层中定义了我的 UpdateStatus 枚举,并且也在 Service 和 Web 层中使用它。想对这种方法发表意见,还是有其他方法可以做到这一点?

请分享您对此的看法。

4

1 回答 1

1

只要您的域模型不离开您应该使用视图模型的 Web API 的边界,就可以了。

于 2013-02-22T07:08:00.803 回答