为什么来自 Postman 时“[FromBody]string json”为 null?

问题描述 投票:0回答:1

当我从单元测试中调用此 API 方法时,

json
参数有一个值。但是当我从 Postman 中执行此操作时,它始终为空。

/// <summary>
/// Save the access integration settings for a given integration.
/// </summary>
/// <param name="json"></param>
/// <param name="integrationID"></param>
/// <returns></returns>
[Route("api/AccessIntegrationSettings/{integrationID}")]
[SwaggerOperation(Tags = new[] { "Access Integration: Integration Settings" })]
public IHttpActionResult Post([FromBody]string json, string integrationID)
{
    ....
}

这就是我在 Postman 中所做的(图片更容易......)

对于标头,有两个安全标头(这不是问题),还有这个:

Content-Type    application/json

我不确定我的方法是否配置不正确,或者邮递员的调用是否错误。但同样,当我从单元测试中点击这个方法时,

json
参数有一个值,所以我倾向于认为我在 Postman 中做错了什么,但我不知道是什么。

更新:

我还注意到,如果我验证 ModelState,来自单元测试时总是

true
,来自 Postman 时总是
false

public override void OnActionExecuting(HttpActionContext actionContext)
{
     if (actionContext.ModelState.IsValid == false)
     {
         ....
     }
}

如果我从每次调用中深入了解 ModelState,则来自 Postman 时会出现一个额外的键值对,而来自我的单元测试时则不存在:

key:   json
value: null
c# .net postman
1个回答
2
投票

你应该使用参数绑定,

Asp.Net
会代替你反序列化json。

所以,尝试在动作参数中使用复杂的对象。

public class SampleJson
{
    public bool IntegrationEnabled { get; set; }

    public bool SyncUsers { get; set; }

    //etc...
}

此外,为您的操作添加

HttpPost
属性。

[HttpPost]
public IHttpActionResult Post(SampleJson jsonObject, [FromUri]string integrationID)

编辑

如果你想处理多种类型,你可以像这样合并对象;

public class RootJson
{
    public SampleJson SampleJson { get; set; }

    public AnotherSampleJson AnotherSampleJson { get; set; }
}

您可以检查该属性的简单空控制。

注意:请记住,合并复杂对象会更改 json。它应该被根括号包围。

© www.soinside.com 2019 - 2024. All rights reserved.