将JSON嵌套对象传递给Post()方法 - C#WebAPI

时间:2017-08-08 15:54:42

标签: c# json asp.net-web-api

我有一个C#WebAPI(我是Web API的新手),它可以很好地工作,因为我可以执行GET&使用HttpClient从Postman和另一个C#程序发出POST请求。

POST方法是"工作"因为我在其中放入一个断点来检查它是否在我发送POST请求时触发了它的代码,它就是。

另一个C#计划"负责从数据库读取一些数据,将其序列化(使用JSON.Net)&将其发送到网络API。

在Web API中,我想使用JSON序列化对象(其中包含嵌套对象)来重建序列化和发送之前的同一个对象。用于创建此对象的每个类都存在于webAPI程序中。

我认为我只需要接收JSON字符串,然后将其反序列化为我的对象,但是我没有实现这个字符串,而是得到了' null'作为post参数。

我的代码:

WebAPI配置

public static class SHPC_APIConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "ShPcAPI",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {id = RouteParameter.Optional}
        );

        // Configure JSON formatter
        var jsonFormatter = config.Formatters.JsonFormatter;
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

控制器

public class DataController : ApiController
{
    public string Get()
    {
        return "Hello world!";
    }

    public HttpResponseMessage Post([FromBody] string value)
    {
        var data = JsonConvert.DeserializeObject<Data>(value);
        Console.WriteLine(value != string.Empty ? "OK" : "KO");
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

执行GET请求有效,我得到了我期望的答案。无论我在哪里向Postman或我的其他C#程序请求。

但是,当我尝试执行POST请求时,请求的参数值始终为null,无论我从Postman还是从其他C#程序请求。

1 个答案:

答案 0 :(得分:2)

在你的WebApiConfig文件中进入App_Start尝试把它放在Register函数中:

var settings = 
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;

这将序列化json中的所有响应。

相关问题