44

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

4

8 回答 8

60

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

您可以使用此读取服务器上的 JSON 对象

string json = new StreamReader(context.Request.InputStream).ReadToEnd();
于 2012-01-03T15:16:33.053 回答
27

以下解决方案对我有用:

客户端:

        $.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;
           }
        }
    }
于 2011-07-08T18:55:33.387 回答
4

如果您向服务器发送数据,$.ajax则数据不会自动转换为 JSON 数据(请参阅如何构建 JSON 对象以发送到 AJAX WebService?)。因此,您可以使用contentType: "application/json; charset=utf-8"anddataType: "json"并保持不要使用JSON.stringifyor转换数据$.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服务器端的使用。

于 2010-06-01T10:57:25.723 回答
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; } }
}
于 2013-09-12T09:44:40.080 回答
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";
}
于 2010-09-20T20:10:37.583 回答
0

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

添加 verb="*" path="test.api" type="test"url: "/test.ashx"替换为 url: "/test.api"

于 2010-09-21T12:16:46.327 回答
-1

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

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

我明白了!

于 2010-08-05T10:54:26.040 回答
-4

尝试System.Web.Script.Serialization.JavaScriptSerializer

通过转换为字典

于 2010-06-01T09:43:18.990 回答