在C#中从POST请求读取和解析JSON数据

Ali*_*sam 3 c# ajax jquery post json

我正在通过JQuery的Ajax做一个POST请求,其中定义的数据类型json包含要发布到服务器的值,类似于Username: "Ali".

我需要在Handler中做的是读取值,将它们反序列化为一个名为的对象User.

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

在调试时,值data如下:

Username=Ali&Age=2....

现在我确定这不是JSON,所以下一行肯定会产生错误:

"Unexpected character encountered while parsing value: U. Path '', line 0, position 0."
Run Code Online (Sandbox Code Playgroud)

JSON从POST请求中读取数据的正确方法是什么?

客户端

$.ajax({
    type: 'POST',
    url: "http://localhost:38504/DeviceService.ashx",
    dataType: 'json',
    data: {
      Username: 'Ali',
      Age: 2,
      Email: 'test'
    },
    success: function (data) {
    },
    error: function (error) {
    }
  });
Run Code Online (Sandbox Code Playgroud)

Wil*_*mer 5

将您的对象转换为json字符串:

$.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) {
    }
  });
Run Code Online (Sandbox Code Playgroud)