【问题标题】:WebApi Controller returned value in Entity Framework 5 and MVC 4 projectWebApi 控制器在 Entity Framework 5 和 MVC 4 项目中返回值
【发布时间】:2012-10-24 00:59:40
【问题描述】:

我正在 MVC 4 项目中处理 webapi、EF5、Windsor Castle,我有一个问题......我应该在 Get 方法中返回实体(或 DTO)还是应该返回 HttpResponseMessage?有什么更好、更标准的方法?

那么,是这个吗?

[System.Web.Http.HttpGet]
public HttpResponseMessage GetById(long id)
{
    var branch = Uow.Branches.GetById(id);
    if (branch != null)
    {
        Request.CreateResponse(HttpStatusCode.OK, branch);
    }

    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}

还是这个?

[System.Web.Http.HttpGet]
public Branch GetById(long id)
{
    var branch = Uow.Branches.GetById(id);
    if (branch != null) return branch ;
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-web-api


    【解决方案1】:

    我将返回包装在 HttpResponseMessage 中的 DTO,如下所示:

    return this.Request.CreateResponse(HttpStatusCode.OK, branch);
    

    DTO/ViewModel 将允许仅发送所需的属性。

    HttpResponseMessage 允许发送额外的状态码,例如在输入无效的情况下,我们可以发送 statusCode precondition failed。

    if (model.EventDate == null)
                {
                    var responseMessage = new HttpResponseMessage();
                    responseMessage.StatusCode = HttpStatusCode.PreconditionFailed;
                    responseMessage.ReasonPhrase = "Please enter valid EventDate input";
                    return responseMessage;
    
                }
    

    【讨论】:

      【解决方案2】:

      视情况而定。但是,在您的示例中,由于 Get 操作的两个版本产生相同的响应,因此我将返回实体分支而不是 HttpResponseMessage。这是因为该框架将帮助抽象出 HttpResponseMessage 的实际创建,因此该操作更侧重于业务逻辑。

      如果您需要对响应消息进行更多控制(即设置不同的状态代码),那么我将改为返回 HttpResponseMessage。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-18
        • 1970-01-01
        • 2017-01-05
        • 2014-03-21
        • 2015-09-06
        • 1970-01-01
        • 2012-12-12
        • 1970-01-01
        相关资源
        最近更新 更多