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 parameters = new List();
                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;

/// 
/// HTTPHandler 的摘要说明
/// 
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 parameters = new List();
                /*
                 例如: 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 : 
中默认的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

你可能感兴趣的:(asp.net/asp.net,mvc/C#)