【问题标题】:ASP.NET - Passing JSON from jQuery to ASHXASP.NET - 将 JSON 从 jQuery 传递到 ASHX
【发布时间】:2011-02-26 06:40:11
【问题描述】:

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

【问题讨论】:

标签: asp.net ajax ashx


【解决方案1】:

试试System.Web.Script.Serialization.JavaScriptSerializer

通过转换为字典

【讨论】:

  • 感谢您的回复。你能详细说明一下吗?我应该序列化什么对象?
  • @colin,我更喜欢字典,但您可以保留任何对象,例如在您的示例中:class MyObj{ public String file, type; }
【解决方案2】:

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

你可以用这个读取服务器上的JSON对象

string json = new StreamReader(context.Request.InputStream).ReadToEnd();

【讨论】:

  • 这是最重要的 5 美分。如果您不介意,我想添加它。
  • @Claudio Redi 请帮我解决这个问题...stackoverflow.com/questions/24732952/…
  • 这只是将 JSON 添加到字符串变量中。您将如何解析此字符串中的数据?如果这是一个包含对象数组的对象怎么办?
  • @CodedContainer 这个问题不包括那个......但是你需要反序列化字符串。看到这个stackoverflow.com/questions/10350982/…
【解决方案3】:
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】:

    以下解决方案对我有用:

    客户端:

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

    【讨论】:

    • 这样对我不起作用,而是:string myName = context.Request["firstName"];
    • @Jaanus 你在使用 POST 吗?
    • @Andre 我可以得到 { firstName: 'stack', lastName: 'overflow' } 完整字符串。我不需要分裂。请给个解决方案stackoverflow.com/questions/24732952/…
    【解决方案5】:

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

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

    【讨论】:

      【解决方案6】:

      这适用于调用网络服务。不确定.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";
      }
      

      【讨论】:

        【解决方案7】:

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

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

        我搞定了!

        【讨论】:

          【解决方案8】:

          如果您向服务器发送关于$.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

          【讨论】:

          • 感谢您的回复。我遇到的问题是在使用 ASHX 页面时无法将 JSON 数据放入请求对象中。 context.Request.QueryString["file"] 的值始终为空。您知道如何将 JSON 数据放入请求中吗?
          • 为了能够看到带有context.Request.QueryString["file"]file 参数,您应该像data: {file:'dave', type:'ward'} 一样使用data(见我的回答)。然后将定义名称为filetype 的查询参数,并将发布到服务器的数据编码为file=dave?type=ward
          • 如果您的 AJAX 正在发布,那么数据将在 Request.Form 属性中,而不是 QueryString。
          • @dave thieben:你是对的。谢谢你的建议。我自己不使用 ASHX。因此,Request.Form 代替 Request.QueryString 会更好。在我看来,Request.Params 是最好的方法,因为它适用于 GET 和 POST(请参阅 msdn.microsoft.com/en-us/library/…
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-01
          • 2013-11-08
          相关资源
          最近更新 更多