Restful API调用传入一个null对象

时间:2017-05-09 14:25:18

标签: json asp.net-mvc api model-view-controller model

我有一个MVC应用程序调用API来更新或返回数据到用户屏幕。当我调用API时,它传入一个null对象。我调试了代码并且数据很好并且在调用API之前适合模型,所以我似乎无法找到它为空的原因。所有其他API调用都可以正常工作,这是我通过对象传递的唯一一个。

我使用Postman调用API并且它工作得很好,我也使用fiddler来查找从应用程序调用时发送到API的json是什么,它有相同的设置和json我与邮递员一起使用。我尝试将[FromBody]添加到API控制器中,并将参数更改为JObject以查看是否可以获取任何内容。任何一个想法?

以下是我使用邮递员和应用程序时发送给API的内容,两者都是相同的:

POST http://localhost/HealthStatusAPI/api/ConfigUpdate HTTP/1.1
Content-Type: application/json; charset=utf-8
Accept: application/json
Accept-encoding: gzip, deflate
Connection: keep-alive

{"MsgConfigUpdate":[{"Address":"http://EndpointURL1/EndpointService1.svc","Active":true}]}

型号:

public class ConfigUpdateList
{
    public List<ConfigUpdate> MsgConfigUpdate { get; set; }
}

public class ConfigUpdate
{
    public string Address { get; set; }

    public bool Active { get; set; }
}

API控制器方法:

public class ConfigUpdateController : ApiController
{
    private IMonitorActions monitorActions;

    public ConfigUpdateController(IMonitorActions monitorActions)
    {
        this.monitorActions = monitorActions;
    }

    public IHttpActionResult PostConfigUpdateList(ConfigUpdateList MsgConfigUpdate)
    {     
        bool result = MonitorActions.ConfigUpdate(MsgConfigUpdate);

        return Ok(result);
    }
}

MVC应用程序调用:

public async Task<ConfigUpdateList> PostConfigUpdateList(ConfigUpdateList MsgConfigUpdate)
{
    using (var client = SetUpHttpClient())
    {

        HttpResponseMessage response = await client.PostAsJsonAsync("api/ConfigUpdate", MsgConfigUpdate);

        if (response.IsSuccessStatusCode)
        {
            try
            {

            }
            catch (Exception ex)
            {

            }
        }                           
    }
}

SetUpHTTPClient方法:

private HttpClient SetUpHttpClient()
    {            
        var client = new HttpClient();
        string RootAddress = _config["SecureAppSettings:ApiRootAddress"];
        TimeSpan timeout = new TimeSpan(0, 0, 0, 10, 0); //10 seconds
        client.Timeout = timeout;
        client.BaseAddress = new Uri(RootAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));            
        client.DefaultRequestHeaders.Authorization = CreateBasicCredentials(sUserName, sPassword);

        return client;
    }

1 个答案:

答案 0 :(得分:0)

修改API方法签名,如:

自:

public IHttpActionResult PostConfigUpdateList(ConfigUpdateList MsgConfigUpdate)

要:

public IHttpActionResult PostConfigUpdateList([FromBody]ConfigUpdateList MsgConfigUpdate)