【问题标题】:Ajax call to asp.net c# method returning custom object listAjax调用asp.net c#方法返回自定义对象列表
【发布时间】:2014-10-27 14:37:05
【问题描述】:

我正在尝试调用此 WebMethod:

[System.Web.Services.WebMethod]
public static List<CustomObject> Carica(int ID)
{
    List<CustomObject> elenco = new List<CustomObject>();
    try
    {
        elenco = GetElencoByID(ID);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return elenco;
}

使用 Ajax:

function caricaElenco(ID) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "nomePagina.aspx/Carica",
        data: '{ID:' + ID + '}',
        dataType: "json",
        success: function (response) {
            for (var i = 0; i < response.d.length; i++) {
                alert(response.d[i].nomeCampo);
            }
        },
        error: function (result) {
            alert("Errore! " + result.status + " - " + result.statusText);
        }
    });
}

但我总是收到错误 500,即使调试服务器代码,他也在做他的工作并返回列表。如果我只是为了测试修改返回单个对象的函数:

public static CustomObject Carica(int ID)
    {
        (...)
        return elenco[0];
    }

我能做到:

success: function (response) {
            alert(response.d.nomeCampo);                    
        }
    },

它正在工作!我还尝试将方法签名更改为:

public static IENumerable<CustomObject> Carica(int ID)

但仍然没有运气.. ajax 和自定义对象列表有问题(对象是 [Serializable]?

更新:

现在我已经:

[System.Web.Services.WebMethod]
public static void Carica(int ID)
{
    List<CustomObject> elenco = new List<CustomObject>();
        try
        {
            elenco = GetElencoByID(ID);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
               new System.Web.Script.Serialization.JavaScriptSerializer();

        string result = jSearializer.Serialize(flussi);
        System.Web.HttpContext.Current.Response.ContentType = "application/json";
        System.Web.HttpContext.Current.Response.Write(result);
        System.Web.HttpContext.Current.Response.End();
    }

但仍然得到“Errore!500 - Internal Server Error”,但调试服务器代码没有错误,我可以在结果值中看到 [{"ID":1,"campo1":null,"campoData":"/Date (1410166675790)/","campoInt":3858.62},{"ID":2,"campo1":null,"campoData":"/Date(1410166675790)/","campoInt":3858.62} (...) ].
如果我评论 Response.End() (只是为了尝试)我得到“Errore!200 - OK”

更新 2:

好的,我已经安装了 Fiddler,错误 500 实际上是指 Response.End() 附带的 ThreadAbortException。使用返回 List 的方法返回原始代码,这是真正的问题... 异常消息:使用 JSON JavaScriptSerializer 进行序列化或反序列化期间出错。字符串长度超过 maxJsonLength 属性设置的值。

更新 3:

好的,我看过这个:Ajax request returns 200 OK, but an error event is fired instead of success 和这个:jQuery AJAX status "200 OK", but no data response,为什么我可以正常但没有成功评论 Response.End().. 我不知道我是否可以把整个JSON 中的列表也将 maxJsonLength 设置为 Int32.MaxValue,因为实际上是一个包含 2437 个元素的列表,其中包含很多字段..

【问题讨论】:

  • 我总是从我的 Web 服务返回 JSON,以前从未尝试过 List。我发现了这个:dotnetcurry.com/showarticle.aspx?ID=320
  • WebMethod 已被 Microsoft 弃用。您应该查看ASP.NET Web API。它得到更好的支持、更易于使用且更简洁。
  • 他们在工作中使用 Framework 3.5,所以没有 Web API.. 现在我正在尝试使用 JavaScriptSerializer..
  • @Rick S 我现在才看到您已经发布了带有评论的链接!可能正是这个问题,因为我有同样奇怪的日期,但无法在工作中安装插件..
  • 您需要下载使用Fiddler2。它会告诉您遇到的 500 错误的详细信息。

标签: c# jquery asp.net ajax list


【解决方案1】:

我在使用 WebMethod 时发现有时需要强制它返回 JSON。你失去了内容协商(除非你手动实现它)。如果可能的话,我仍然建议切换到Web API。但这应该可以解决问题。

[System.Web.Services.WebMethod]
public static void Carica(int ID)
{
    List<CustomObject> elenco = new List<CustomObject>();
    try
    {
        elenco = GetElencoByID(ID);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    Response.ContentType = "application/json";
    Response.Write(JsonConvert.SerializeObject(elenco)); //using JSON.NET, but any serializer should do
    Response.End();
}

因此,您将其切换为 void 作为返回类型。然后将响应的内容类型设置为 JSON。然后手动将您的“返回对象”转换为 JSON 并将其写入响应,然后结束响应。

【讨论】:

  • 我不能使用响应,因为我必须为 ajax 调用声明 WebMethod 静态..
  • @MisterFrank 然后使用HttpContext.Current.Response
【解决方案2】:

在 Web.Config 中设置:

<system.web.extensions>
    <scripting>
      <webServices>
          <jsonSerialization maxJsonLength="2147483647"/>
      </webServices>
    </scripting>
</system.web.extensions>

基于此:

Can I set an unlimited length for maxJsonLength in web.config?

现在它可以使用原始的 WebMethod。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2012-01-07
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多