Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and Parse JSON data from POST request in C#

I'm doing a POST request via JQuery's Ajax, with the type of data defined as json, containing the values to be posted to server, something like Username: "Ali".

What I need to do in a Handler, is to read the values, deserialize them to an object named User.

String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
User user = JsonConvert.DeserializeObject<User>(data);

While debugging, the value of data is the following:

Username=Ali&Age=2....

Now I'm sure this isn't JSON, so the next line would certainly produce an error:

"Unexpected character encountered while parsing value: U. Path '', line 0, position 0."

What is the proper way to read JSON data from POST request?

Client Side

$.ajax({
    type: 'POST',
    url: "http://localhost:38504/DeviceService.ashx",
    dataType: 'json',
    data: {
      Username: 'Ali',
      Age: 2,
      Email: 'test'
    },
    success: function (data) {
    },
    error: function (error) {
    }
  });
like image 476
Ali Bassam Avatar asked Jun 27 '26 19:06

Ali Bassam


1 Answers

Convert your object to json string:

$.ajax({
    type: 'POST',
    url: "http://localhost:38504/DeviceService.ashx",
    dataType: 'json',
    data: JSON.stringify({
      Username: 'Ali',
      Age: 2,
      Email: 'test'
    }),
    success: function (data) {
    },
    error: function (error) {
    }
  });
like image 112
Wilmer Avatar answered Jun 30 '26 07:06

Wilmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!