REST Web服务 - 获取和创建的不同类型

Jos*_*Noe 2 c# rest web-services asp.net-web-api

使用ASP.Net Web Api,您的GET端点返回与POST端点接受的不同类型是否正常/良好实践?

在许多情况下,我们想要在GET中返回的字段不能在POST中设置,例如"LastUpdated","Total"等,需要不同的类型?

例如,GET返回ReservationForGetModel,而POST接受ReservationForCreateModel:

public class ReservationController : ApiController {
...

  public HttpResponseMessage Get(int id) {
    Reservation reservation = _reservationService.Get(id);
    //map Reservation to ReservationForGetModel
    //return ReservationForGetModel
  }

  public HttpResponseMessage Post(ReservationForCreateModel reservation) {
    //create reservation using ReservationForCreateModel here
    //return 201 with location header set
  }

}
Run Code Online (Sandbox Code Playgroud)

Dar*_*ler 5

GET和POST可以使用完全不同的媒体类型.考虑HTML表单:POST with application/x-www-urlencoded-form和GET返回text/html.

使用GET和PUT,媒体类型更可能是对称的,但这并不是一个严格的规则.

  • @bryanmac您能为该声明提供参考吗?我的理解是资源可以有许多不同的表示.您认为违反了什么REST约束? (2认同)