ashx接收传递的json

前端代码

 function sub() {
            var par = JSON.stringify({title: "a", info: "ifno", age: 123 });
            console.log(par);
            $.ajax({
                type: "POST",
                url: "abc.ashx", 
                data: par,//数据,json字符串
                async: false,
                contentType: "application/json",
                dataType: "json",
                success: function(result) {
                    alert(result);
                }
            });
        }

后台ashx代码:

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

            string result;//获取json字符串
            using (var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }

            context.Response.Write("Hello World");
}

C#提交json post请求代码:

        /// 
        /// json请求
        /// 
        /// 
        /// 
        /// 
        public static string PostRequestJson(string url, string json)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method = "POST";
            req.ContentType = "application/json; charset=utf-8";
            byte[] data = Encoding.UTF8.GetBytes(json);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            string result;
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }

            return result;
        }

你可能感兴趣的:(ashx接收传递的json)