WebApi Controller returned value in Entity Framework 5 and MVC 4 project

后端 未结 2 1215
挽巷
挽巷 2021-01-26 08:25

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 HttpRespons

2条回答
  •  孤街浪徒
    2021-01-26 08:54

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

提交回复
热议问题