Getting a deserialized Json object as a string in a Web API controller

Below is my Json input from Ui:

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

I can get it without problems in the structure of objects 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 goal is to get the following API method:

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

The reason for this requirement is that I do not use a Json object that is de-serialized through the Web API, I just need to store the actual Json in the database and retrieve and return to the Ui that will parse it.

As I can’t get in the input line, as suggested, so I have to perform an additional step of Json serialization, de-serialization to achieve the goal. Any mechanism for me to avoid this workaround completely by getting in line and using it directly. I am currently testing Postman

+5
source share
1 answer

You can read the contents of the body directly as a string, regardless of what you entered in the parameters of your method. You really do not need to enter anything into 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 do not need to read input as a parameter.

+5
source

Source: https://habr.com/ru/post/1246698/


All Articles