C# 继承IHttpHandler接收$.ajax的post过来的参数

写一个类继承IHttpHandler,想接收前台页面$.ajax的post传过来的参数,用context.Request.Form,context.Request.Params一直不行。网上查了查,原来是因为contentType: "application/json; charset=utf-8"的原因。找到一个解决方案:context.Request.InputStream转成json。

ajax

$.ajax({
            type: "POST",
            url: '/WeMain/GetXXX',
            data: "{'weuser': '" + username + "'}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (res) {
                alert(res);
            },
            error: function (jqXHR) {
                alert("失败" + JSON.stringify(jqXHR));
            }
        });

post

$.post("/WeMain/GetXXX", { weuser: username }, function (result) {
            alert(result);
        });

get

$.get("/WeMain/GetXXX", { weuser: username }, function (data, status) {
            alert("Data: " + data + "nStatus: " + status);
        });

主要代码:

List<object> parameters = new List<object>();
                Stream stream = context.Request.InputStream;
                if(stream.Length!=0)
                {
                    StreamReader rd = new StreamReader(stream);
                    string json = rd.ReadToEnd();
                    JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json);
                    //单层json
                    foreach (JToken child in obj.Children())
                    {
                        var property1 = child as JProperty;
                        parameters.Add(property1.Value.ToString());
                    }
                }

HTTPHandler

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.SessionState;

/// <summary>
/// HTTPHandler 的摘要说明
/// </summary>
public class HTTPHandler : IHttpHandler, IRequiresSessionState
{    
    private string typeName;
    private string methodName;
    public HTTPHandler(string TypeName, string MethodName)
    {
        try
        {
            typeName = TypeName;
            methodName = MethodName;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var ass = this.GetType().Assembly;
            var instance = ass.CreateInstance(typeName);
            if (instance != null)
            {
                var tp = instance.GetType();
                var method = tp.GetMethod(methodName);
                List<object> parameters = new List<object>();
                /*
                 例如: Content-Type: text/html;charset:utf-8;

                 常见的媒体格式类型如下:
                        text/html : HTML格式
                        text/plain :纯文本格式     
                        text/xml :  XML格式
                        image/gif :gif图片格式   
                        image/jpeg :jpg图片格式
                        image/png:png图片格式

                   以application开头的媒体格式类型:
                       application/xhtml+xml :XHTML格式
                       application/xml     : XML数据格式
                       application/atom+xml  :Atom XML聚合格式   
                       application/json    : JSON数据格式
                       application/pdf       :pdf格式 
                       application/msword  : Word文档格式
                       application/octet-stream : 二进制流数据(如常见的文件下载)
                       application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
                */
                if (context.Request.ContentType.Contains("application/json"))
                {
                    ParameterInfo[] paramInfos = method.GetParameters();
                    if (context.Request.RequestType.ToUpper() == "POST")
                    {
                        #region MyRegion                    
                        Stream stream = context.Request.InputStream;
                        if (stream.Length != 0)
                        {
                            StreamReader rd = new StreamReader(stream);
                            string json = rd.ReadToEnd();
                            JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json);
                            //单层json
                            foreach (JToken child in obj.Children())
                            {
                                var property1 = child as JProperty;
                                parameters.Add(property1.Value.ToString());
                            }
                        }
                        #endregion
                    }
                    else if (context.Request.RequestType.ToUpper() == "GET")
                    {
                        context.Request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                        foreach (var item in paramInfos)
                        {
                            parameters.Add(context.Request.QueryString[item.Name]);
                        }
                    }
                    else
                    {
                        foreach (var item in paramInfos)
                        {
                            parameters.Add(context.Request.Params[item.Name]);
                        }
                    }                    
                }
                else
                {
                    ParameterInfo[] paramInfos = method.GetParameters();
                    if (context.Request.RequestType.ToUpper() == "POST")
                    {
                        foreach (var item in paramInfos)
                        {
                            parameters.Add(context.Request.Form[item.Name]);
                        }
                    }
                    else if (context.Request.RequestType.ToUpper() == "GET")
                    {
                        foreach (var item in paramInfos)
                        {
                            parameters.Add(context.Request.QueryString[item.Name]);
                        }
                    }
                    else
                    {
                        foreach (var item in paramInfos)
                        {
                            parameters.Add(context.Request.Params[item.Name]);
                        }
                    }
                }
                var rs = method.Invoke(instance, parameters.ToArray());
                context.Response.AppendHeader("charset", "utf-8");
                context.Response.AppendHeader("defaultCharset", "utf-8");
                context.Response.AppendHeader("Content-Type", "text/html; charset=utf-8");
                context.Response.Write(rs.ToString());
            }
        }
        catch (Exception ex)
        {
            context.Response.Write("Server HttpHandler Error:" + ex);
        }
    }
}

参考:

https://www.cnblogs.com/zhy-1992/p/8421451.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值