ASP.NET - 将JSON从jQuery传递到ASHX

col*_*bes 42 asp.net ajax ashx

我正在尝试将JSON从jQuery传递到.ASHX文件.下面的jQuery示例:

$.ajax({
      type: "POST",
      url: "/test.ashx",
      data: "{'file':'dave', 'type':'ward'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",      
    });
Run Code Online (Sandbox Code Playgroud)

如何在.ASHX文件中检索JSON数据?我有方法:

public void ProcessRequest(HttpContext context)
Run Code Online (Sandbox Code Playgroud)

但我在请求中找不到JSON值.

Cla*_*edi 56

我知道这太旧了,但只是为了纪录,我想加5美分

您可以使用此方法读取服务器上的JSON对象

string json = new StreamReader(context.Request.InputStream).ReadToEnd();
Run Code Online (Sandbox Code Playgroud)


And*_*dre 24

以下解决方案适合我:

客户端:

        $.ajax({
            type: "POST",
            url: "handler.ashx",
            data: { firstName: 'stack', lastName: 'overflow' },
            // DO NOT SET CONTENT TYPE to json
            // contentType: "application/json; charset=utf-8", 
            // DataType needs to stay, otherwise the response object
            // will be treated as a single string
            dataType: "json",
            success: function (response) {
                alert(response.d);
            }
        });
Run Code Online (Sandbox Code Playgroud)

服务器端.ashx

    using System;
    using System.Web;
    using Newtonsoft.Json;

    public class Handler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string myName = context.Request.Form["firstName"];

            // simulate Microsoft XSS protection
            var wrapper = new { d = myName };
            context.Response.Write(JsonConvert.SerializeObject(wrapper));
        }

        public bool IsReusable
        {
           get
           {
                return false;
           }
        }
    }
Run Code Online (Sandbox Code Playgroud)


Dew*_*wfy -4

尝试System.Web.Script.Serialization.JavaScriptSerializer

通过转换到字典

  • 谢谢回复。您能详细说明一下吗?我应该序列化什么对象? (2认同)