Receiving Json deserialized object as string in Web API controller

陌路散爱 提交于 2019-12-23 12:06:09

问题


Following is my Json input from Ui:

{
    "data": [{
        "Id": 1
    }, {
        "Id": 2
    }, {
        "Id": 3
    }]
}

I can receive it without an issue in the object structure shown below:

   public class TestController : ApiController
    {
        /// <summary>
        /// Http Get call to get the Terminal Business Entity Wrapper
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        [HttpPost]
        [Route("api/TestJsonInput")]
        public string TestJsonInput([FromBody] TestInput input)
        {
            return JsonConvert.SerializeObject(input.data);
        }        

        public class TestInput
        {
            public List<Info> data { get; set; }
        }

        public class Info
        {
            public int Id { get; set; }
        }

    }

However my objective is to receive in following API method:

      [HttpPost]
        [Route("api/TestJsonInput")]
        public string TestJsonInput1([FromBody] string input)
        {
            return input;
        }

Reason for this requirement is, I have no use of the Json object de-serialized via Web API, I just need to persist the actual Json to the Database and fetch and return to Ui, which will parse it back.

As I am not able to receive in the string input as suggested, so I have to carry out extra step of Json serialization, de-serialization to achieve the objective. Any mechanism for me to avoid this workaround totally by receiving in a string and using it directly. I am currently testing using Postman


回答1:


You can read the body content directly as a string regardless of what you put in the parameters of your method. You dont actually need to put anything in the parameters and you can still read the body.

[HttpPost]
[Route("api/TestJsonInput")]
public string TestJsonInput1()
{
    string JsonContent = Request.Content.ReadAsStringAsync().Result;
    return JsonContent;
}

You dont need to read the input as a parameter.



来源:https://stackoverflow.com/questions/36499682/receiving-json-deserialized-object-as-string-in-web-api-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!