的WebAPI控制器在实体框架5和MVC 4项目返回的值 [英] WebApi Controller returned value in Entity Framework 5 and MVC 4 project

查看:147
本文介绍了的WebAPI控制器在实体框架5和MVC 4项目返回的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个的WebAPI,EF5,温莎城堡在MVC 4项目,我有一个问题...我应该返回get方法的实体(或DTO)或者我应该返回的Htt presponseMessage?有什么更好的办法,并做更多的标准的方式?

那么,是不是这样?

  [System.Web.Http.HttpGet]
公众的Htt presponseMessage GetById(长ID)
{
    VAR支= Uow.Branches.GetById(ID);
    如果(分支!= NULL)
    {
        Request.CreateResponse(的HTTPStatus code.OK,分支机构);
    }    抛出新的Htt presponseException(新的Htt presponseMessage(的HTTPStatus code.NotFound));
}

或者这样?

  [System.Web.Http.HttpGet]
公共科GetById(长ID)
{
    VAR支= Uow.Branches.GetById(ID);
    如果(!分支= NULL)返回分支;
    抛出新的Htt presponseException(新的Htt presponseMessage(的HTTPStatus code.NotFound));
}


解决方案

我将返回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;

            }

这篇关于的WebAPI控制器在实体框架5和MVC 4项目返回的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆