ASP.NET - 将JSON从jQuery传递到ASHX

时间:2010-06-01 09:35:18

标签: asp.net ajax ashx

我正在尝试将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值。

8 个答案:

答案 0 :(得分:55)

我知道这太旧了,但仅仅是为了记录我想加5美分

您可以使用此

读取服务器上的JSON对象
string json = new StreamReader(context.Request.InputStream).ReadToEnd();

答案 1 :(得分:24)

以下解决方案对我有用:

客户端:

        $.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;
           }
        }
    }

答案 2 :(得分:4)

如果您将数据发送到服务器$.ajax,数据将不会自动转换为JSON数据(请参阅How do I build a JSON object to send to an AJAX WebService?)。因此,您可以使用contentType: "application/json; charset=utf-8"dataType: "json",并且不要使用JSON.stringify$.toJSON转换数据。而不是

data: "{'file':'dave', 'type':'ward'}"

(手动将数据转换为JSON)您可以尝试使用

data: {file:'dave', type:'ward'}

使用context.Request.QueryString["file"]context.Request.QueryString["type"]结构获取服务器端的数据。如果您确实以这种方式遇到一些问题,那么您可以尝试使用

data: {file:JSON.stringify(fileValue), type:JSON.stringify(typeValue)}

和服务器端的使用DataContractJsonSerializer

答案 3 :(得分:2)

html
<input id="getReport" type="button" value="Save report" />

js
(function($) {
    $(document).ready(function() {
        $('#getReport').click(function(e) {
            e.preventDefault();
            window.location = 'pathtohandler/reporthandler.ashx?from={0}&to={1}'.f('01.01.0001', '30.30.3030');
        });
    });

    // string format, like C#
    String.prototype.format = String.prototype.f = function() {
        var str = this;
        for (var i = 0; i < arguments.length; i++) {
            var reg = new RegExp('\\{' + i + '\\}', 'gm');
            str = str.replace(reg, arguments[i]);
        }
        return str;
    };
})(jQuery);

c#
public class ReportHandler : IHttpHandler
{
    private const string ReportTemplateName = "report_template.xlsx";
    private const string ReportName = "report.xlsx";

    public void ProcessRequest(HttpContext context)
    {
        using (var slDocument = new SLDocument(string.Format("{0}/{1}", HttpContext.Current.Server.MapPath("~"), ReportTemplateName)))
        {
            context.Response.Clear();
            context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", ReportName));

            try
            {
                DateTime from;
                if (!DateTime.TryParse(context.Request.Params["from"], out from))
                    throw new Exception();

                DateTime to;
                if (!DateTime.TryParse(context.Request.Params["to"], out to))
                    throw new Exception();

                ReportService.FillReport(slDocument, from, to);

                slDocument.SaveAs(context.Response.OutputStream);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                context.Response.End();
            }
        }
    }

    public bool IsReusable { get { return false; } }
}

答案 4 :(得分:1)

这适用于调用Web服务。不确定.ASHX

$.ajax({ 
    type: "POST", 
    url: "/test.asmx/SomeWebMethodName", 
    data: {'file':'dave', 'type':'ward'}, 
    contentType: "application/json; charset=utf-8",   
    dataType: "json",
    success: function(msg) {
      $('#Status').html(msg.d);
    },
    error: function(xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert('Error: ' + err.Message);
    }
}); 



[WebMethod]
public string SomeWebMethodName(string file, string type)
{
    // do something
    return "some status message";
}

答案 5 :(得分:0)

您必须在Web配置文件中定义处理程序属性以处理用户定义的扩展请求格式。这里用户定义的扩展名是“ .api”

add verb =“*”path =“test.api”type =“test” url:“/ test.ashx”替换为 url:“/ test.api”

答案 6 :(得分:-1)

如果使用$ .ajax并使用.ashx来获取查询字符串,请不要设置数据类型

$.ajax({ 
    type: "POST", 
    url: "/test.ashx", 
    data: {'file':'dave', 'type':'ward'}, 
    **//contentType: "application/json; charset=utf-8",   
    //dataType: "json"**    
}); 

我明白了!

答案 7 :(得分:-4)

尝试System.Web.Script.Serialization.JavaScriptSerializer

投射到字典