代码之家  ›  专栏  ›  技术社区  ›  phonemyatt

JSON API.Net核心Put和补丁示例

  •  0
  • phonemyatt  · 技术社区  · 7 年前

    我正在用 json:api 来自github repo的规范 {json:api} . GET的端点(带或不带查询)、POST&当我从邮递员处发送邮件时,DELETE正在按预期工作。但我找不到使用PUT或PATCH更改现有资源的工作示例。当我发送带有数据的补丁请求时,它会返回响应“200OK”,但在数据库中并没有改变。以下是我的请求和回复。

      Request GET : http://localhost:5000/api/people -> 200 OK
      Response : [
      {
        "name": "Samuel",
        "articles": null,
        "id": 2,
        "stringId": "2"
      },
      {
        "name": "John",
        "articles": null,
        "id": 3,
        "stringId": "3"
      },
      {
        "name": "Robbin",
        "articles": null,
        "id": 4,
        "stringId": "4"
       } ]
    
      Request GET: http://localhost:5000/api/people/2 -> 200 OK
      Response : {
       "name": "Samuel",
       "articles": null,
       "id": 2,
       "stringId": "2" 
      }
    
      Request GET: http://localhost:5000/api/people/2?include=articles -> 200 OK
      Response : {
       "name": "Samuel",
       "articles": [],
       "id": 2,
       "stringId": "2" 
      }
    
      Request POST: http://localhost:5000/api/people -> 201 Created
      Request Body: {"name":"Samuel"}
      Response : {
       "name": "Samuel",
       "articles": null,
       "id": 2,
       "stringId": "2" 
      }
    
      Request DELETE: http://localhost:5000/api/people/2 -> 204 No Content
    

    2 回复  |  直到 7 年前
        1
  •  2
  •   phonemyatt    7 年前

    在阅读了JSONAPI和OData的规范文档之后,我做出了最终决定。为了更好地理解我自己的代码,我将坚持使用我自己的格式,我建议使用Swagger作为Api文档。如果规范不符合我的要求,即使人们告诉我这是标准,这也没有意义。

        2
  •  1
  •   phonemyatt    7 年前

    我在文档中发现,对于不同的api调用和body请求,需要包含以下两个标题,对于补丁,这两个标题也是不同的。

    "Accept: application/vnd.api+json"       <--- This needs to put in header
    "Content-Type: application/vnd.api+json" <--- This also needed.
    
    Request PATCH: http://localhost:5000/api/people/3 -> 200 OK
    // Request body becomes text, anybody knows how to format to JSON?
    Request Body(Text): {
     "data": {
      "type": "people",
      "attributes": {
           "name": "John"
         }
       }
    }
    
    Response : {
          "data": {
             "attributes": {
            "name": "John"
        },
          "relationships": {
            "articles": {
                "links": {
                    "self": 
                "http://localhost:5000/api/people/3/relationships/articles",
                    "related": "http://localhost:5000/api/people/3/articles"
                }
            }
           },
              "type": "people",
              "id": "3"
           } }