且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

的WebAPI控制器在实体框架5和MVC 4项目返回的值

更新时间:2023-02-13 09:37:32

我将返回DTO包裹在Htt的presponseMessage如下:

 返回this.Request.CreateResponse(的HTTPStatus code.OK,分支机构);

DTO /视图模型将使只发送所需的属性。

Htt的presponseMessage允许发送附加状态code,例如在输入无效的情况下,我们可以发送状态code precondition失败。

 如果(model.EventDate == NULL)
            {
                VAR responseMessage =新的Htt presponseMessage();
                responseMessage.Status code =的HTTPStatus code preconditionFailed。
                responseMessage.ReasonPhrase =请输入有效的EVENTDATE输入;
                返回responseMessage;            }

I'm working on a webapi, EF5, Windsor Castle in a MVC 4 project, and I have a question...should I return the Entity (or DTO) in the Get method or Should I return an HttpResponseMessage? What's the better way and more standard way to do it?

So, Is it this?

[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));
}

Or this?

[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));
}

I will return DTO wrapped in HttpResponseMessage as below:

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

DTO/ViewModel will enable to send only required properties.

HttpResponseMessage allow to send additional status code, for example in case of invalid input, we can send statusCode precondition failed.

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

            }