【问题标题】:How to return a JSON object in standard web forms .Net如何在标准 Web 表单.Net 中返回 JSON 对象
【发布时间】:2011-12-25 17:50:07
【问题描述】:

目标是调用一个方法,然后返回一个 JSON 对象。

我是 JSON 新手。

我有一个 default.aspx,其中包含以下代码。现在我想要 Default.aspx.cs 中的一个普通方法在这里的点击事件上运行。

$(".day").click(function (event) {
var day = $(event.currentTarget).attr('id');
if (day != "") {
    $.ajax(
    {
        type: "POST",
        async: true,
        url: 'Default.aspx?day=' + day,
        data: day,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            console.log("SUCCESS:" + msg);
            //  $(".stripp img").attr('src', "data:image/jpg;" + msg);
            //  $(".stripp").show();
        },
        error: function (msg) {
            console.log("error:" + msg);
        }
    });
}

});

Default.aspx.cs 与此类似:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["day"] != null)
            GetFile(Request.QueryString["day"]);
    }
    public string GetFile(string day)
    {
        string json = "";
        byte[] bytes = getByteArray();

        json = JsonConvert.SerializeObject(bytes);
        return json;
    }

我哪里错了? 我应该以某种方式使用它还是仅适用于 Web 服务?

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

【问题讨论】:

    标签: jquery asp.net ajax json webforms


    【解决方案1】:

    我建议HttpHandler。没有页面生命周期(因此速度非常快),代码分离更清晰,并且可重用。

    向您的项目添加一个“通用处理程序”类型的新项目。这将创建一个新的 .ashx 文件。任何实现IHttpHandler 的类的主要方法是ProcessRequest。因此,要使用原始问题中的代码:

    public void ProcessRequest (HttpContext context) {
    
        if(String.IsNullOrEmpty(context.Request["day"]))
        {
            context.Response.End(); 
        }
    
        string json = "";
        byte[] bytes = getByteArray();
    
        json = JsonConvert.SerializeObject(bytes);
        context.Response.ContentType = "text/json";
        context.Response.Write(json);
    }
    

    更改您的 AJAX 调用中的 url 就可以了。 JavaScript 看起来像这样,其中 GetFileHandler.ashx 是您刚刚创建的 IHttpHandler 的名称:

    $.ajax(
        {
            type: "POST",
            async: true,
            url: 'Handlers/GetFileHandler.ashx',
            data: "Day=" + $.toJSON(day),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                console.log("SUCCESS:" + msg);
            },
            error: function (msg) {
                console.log("error:" + msg);
            }
        });
    

    另一个需要考虑的小点,如果您需要从 Handler 代码本身访问 Session 对象,请确保继承自 IRequiresSessionState 接口:

    public class GetFileHandler : IHttpHandler, IRequiresSessionState
    

    【讨论】:

    • 好的,我喜欢这种方法,但是Ajax调用中的URL应该是什么?
    • 我得到:405 Method Not Allowed
    • 您将请求发送到的确切 url 是什么?我之所以这么问,是因为一些谷歌搜索提出了这个问题:只有当您使用 Microsoft Internet Information Services (IIS) 4.0 和 Microsoft Internet Information Services 5.0 时才会出现此问题。如果您将 POST 请求发送到运行 IIS 4.0 或 IIS 5.0 的服务器,并且 POST 请求包含以斜杠 (/) 结尾的 URL,则会出现此问题。 IIS 返回 405 错误消息而不是默认文档。但是,如果 Verb 属性的方法值为 GET 或 HEAD,则 IIS 返回默认文档。
    • JSON 文本的 MIME 媒体类型是 application/json。默认编码为 UTF-8。 (来源:RFC 4627)
    【解决方案2】:

    是的,您的方法必须是带有 WebMethod 属性的静态方法

    基本示例:

    CS

    using System;
    using System.Web.Services;
    
    public partial class _Default : System.Web.UI.Page
    {
      [WebMethod(EnableSession=false)]
      public static string HelloWorld()
      {
        return "Hello World";
      }
    }
    

    Javascript

    <script>
        $.ajax({
          type: "POST",
          url: "Default.aspx/HelloWorld",
          data: "{}",
          contentType: "application/json",
          dataType: "json",
          success: function(msg) {
            console.log(msg.d);
          }
        });
    </script>
    

    【讨论】:

    • d从哪里来?
    【解决方案3】:

    自从我使用 webforms 以来已经有一段时间了,但如果没记错的话,如果你将 webmethod 属性放在 GetFile 方法上并将该方法设为静态,它应该可以工作。

     [WebMethod]
     public static string GetFile(string day)
    

    此外,您在 ajax 方法中发布数据的方式有些不妥。从 url 中删除查询字符串 day,数据应为 json 格式,例如 {"day":day}

    【讨论】:

      猜你喜欢
      • 2018-01-04
      • 2019-04-22
      • 1970-01-01
      • 2020-10-06
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      相关资源
      最近更新 更多