POSTMAN Rest客户端中模拟Web API 2的POST请求

37

我正在使用带有属性路由的ASP.NET Web API 2。

我有以下的PlayerModel.

public class PlayerModel
{
    public int Id { get; set; }
    public string Key { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }
    public int TeamId { get; set; }
    public PlayerStatModel Stat{ get; set; }
}


public class PlayerStatModel 
{
    public int PlayerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Title { get; set; }
    public string EmailAddress { get; set; }
    public IEnumerable<PhoneNumberModel> PhoneNumbers { get; set; } 
    public int TeamId { get; set; }
}

public class PhoneNumberModel
{
    public string Value { get; set; }
    public string Extension { get; set; }
}

随后将其传入PostPlayer进行玩家创建。

[HttpPost("", RouteName = "PostPlayer")]
public PlayerModel PostPlayer(PlayerModel player)
{
    var playerObject = this.GetObject(player));
    this._manager.CreatePlayer(playerObject );

    return this.GetPlayer(playerObject.Id);
}

我的集成测试通过了,我能够验证当调用 CreatePlayer 时确实创建了玩家。

我应该如何在 Google Chrome 的 POSTMAN Rest 客户端中建模这个 POST 请求?

enter image description here

1个回答

80

确保您指定了raw并将Content-Type请求头设置为application/json。然后继续指定与您的视图模型结构相匹配的POST请求正文:

{
    "id": 1,
    "key": "some key",
    "name": "some name of course",
    "password": "the hyper secret",
    "teamId": 256,
    "stat": {
        "playerId": 115,
        "firstName": "John",
        "lastName": "Smith",
        "title": "His Royal Majesty",
        "emailAddress": "john.smith@buckingampalace.com",
        "phoneNumbers": [
            { "value": "123", "extension": "05" },
            { "value": "456", "extension": "45" }
        ],
        "teamId": 678
    }
}

因此,你实际的有效负载在协议层面上会是这个样子:

POST /NFL/Players HTTP/1.1
Host: localhost:9888
Content-Type: application/json
Content-Length: 582

{
    "id": 1,
    "key": "some key",
    "name": "some name of course",
    "password": "the hyper secret",
    "teamId": 256,
    "stat": {
        "playerId": 115,
        "firstName": "John",
        "lastName": "Smith",
        "title": "His Royal Majesty",
        "emailAddress": "john.smith@buckingampalace.com",
        "phoneNumbers": [
            { "value": "123", "extension": "05" },
            { "value": "456", "extension": "45" }
        ],
        "teamId": 678
    }
}

你能否进一步解释一下,我遇到了一些小问题。 - NomanJaved
3
在 ASP.net Core 中,在参数前加上 [FromBody] 标记。 - Prageeth godage
这是一篇解释为什么我们应该在 .net API 中使用 [FromBody] 的链接。https://dev59.com/UmAf5IYBdhLWcg3wdCh1 - Ikram Shah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接