ashx接收传递的json
  itZnTtlPpL80 2023年11月02日 58 0

前端代码

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请求代码:

/// <summary>
        /// json请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        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;
        }
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  YDWh1ewos2dL   2023年12月22日   91   0   0 ciJSONcijson
itZnTtlPpL80