我正在尝试将JSON从jQuery传递到.ASHX文件.下面的jQuery示例:
$.ajax({ type: "POST", url: "/test.ashx", data: "{'file':'dave', 'type':'ward'}", contentType: "application/json; charset=utf-8", dataType: "json", });
如何在.ASHX文件中检索JSON数据?我有方法:
public void ProcessRequest(HttpContext context)
但我在请求中找不到JSON值.
我知道这太旧了,但只是为了纪录,我想加5美分
您可以使用此方法读取服务器上的JSON对象
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
以下解决方案适合我:
客户端:
$.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); } });
服务器端.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; } } }