Receiving Json deserialized object as string in We

2019-06-23 19:59发布

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条回答
闹够了就滚
2楼-- · 2019-06-23 20:15

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.

查看更多
登录 后发表回答