Tuesday, February 13, 2018

.NET MVC - Read Json Object From POST data


If you want to get JSON data posted to MVC endpoint without creating corresponding C# object, you can use the following method.

Web API endpoint

 [HttpPost]
        [Route("GetData")]
        public String GetData()
        {
            //Get the request input stream
            Stream req = Request.InputStream;
            req.Seek(0, System.IO.SeekOrigin.Begin);
            string jsonString = new StreamReader(req).ReadToEnd();

            //Convert JSON String to JObject
            JObject jsonObject = JObject.Parse(jsonString);

            //Get posted data
            string name= jsonObject["name"].ToString();
            return name;

        }



JavaScript call

            let jsonData = '{"name":"myname",age:10}';
            let reqPromise = fetch('/GetData',
                {
                    method: "POST",
                    body: jsonData,
                    headers: {
                        'Accept': 'application/json, text/plain, */*',
                        'Content-Type': 'application/json'
                    }
                });

            reqPromise.then(
                (response) => {
                    return response.text();
                }
            ).then((jsonRespnse) => {
                console.log(jsonRespnse);
                }

            );


The other option is to create corresponding C# object and accept it as a parameter in the endpoint.

1) Create object

    public class MyData
    {
        public String Name { get; set; }
        public int Age { get; set; }

    }

2) Accept the object as a parameter using [FromBody] attribute as given below

        [HttpPost]
        [Route("GetData")]
        public String GetData([System.Web.Http.FromBody] MyData myData)
        {
          return myData.Name;
        }



No comments: