【问题标题】:What is the correct REST Urlpattern for POST operationPOST 操作的正确 REST Urlpattern 是什么
【发布时间】:2014-07-04 15:49:12
【问题描述】:

我有 rest url 支持 POST 请求。它看起来像

api/country/{countryId}/state

用于在具有给定 ID 的 国家 中创建 state 资源

但是这个url的映射函数是

public HttpResponseMessage Post(int countryId,StateDto state)
    {
        var country = _countryAppService.AddNewState(state, countryId);
        var message = Request.CreateResponse(HttpStatusCode.Created, country);
        return message;

    }

给定网址的预期样本就像 api/country/1/state(在国家/地区创建一个 id=1 的新州)

但是这里我没有使用上述函数中的url值(1),而不是调用者需要通过请求体传递相应的countryId,即不能保证url中的contryId和post请求相同.所以我的疑问是什么是正确的 url 模式来保存特定国家/地区的状态 vai post request?

【问题讨论】:

    标签: asp.net-mvc rest asp.net-web-api asp.net-web-api2


    【解决方案1】:

    如果资源路径和请求正文中的信息相同,则为信息重复;调用者永远不需要在同一个请求中两次向您传递相同的信息。

    您应该选择一个作为权威来源,而忽略另一个。由于您必须拥有正确的资源地址才能执行操作,我建议您需要从那里获取值:

    public HttpResponseMessage Post(int countryId,StateDto state)
    {
        // Compose the DTO from the route parameter.
        state.CountryId = countryId;
    
        var country = _countryAppService.AddNewState(state);
        var message = Request.CreateResponse(HttpStatusCode.Created, country);
        return message;
    }
    

    【讨论】:

      【解决方案2】:

      你也可以在body中传递StateDto对象,它会在body中,id可以在url中

      public HttpResponseMessage Post([FromUri]int countryId,[FromBody]StateDto state)
          {
              var country = _countryAppService.AddNewState(state, countryId);
              var message = Request.CreateResponse(HttpStatusCode.Created, country);
              return message;
      
          }
      

      只有一个参数可以来自 body ,其他必须来自 uri,你可以在这里阅读更多: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

      在 uri 中传递 stateDto 也是一种选择,但是您必须在查询字符串中传递其所有成员。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-13
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多