5

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 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What about having multiple string inputs, I am assuming this would be one single Json string, which need to be parsed
Also I am not having it in Body now, then how shall I test the same from Postman, where does the input goes in this case
It works for me in the current context, thanks kudos :)
@MrinalKamboj If your not sending it in the body then you just send strings as parameters as normal.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.