1

I'm trying to calling this 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;
}

with 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);
        }
    });
}

But I'm always getting error 500, even if debugging the server code, he's doing his job and returning the list.. If I try just for test to modify the function for returning a single object:

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

I'm able to do:

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

and it's working! I've also tried to change the method signature to:

public static IENumerable<CustomObject> Carica(int ID)

but still no luck.. That's something wrong about ajax and custom object list (the object is [Serializable]?

UPDATE:

Now I've:

[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();
    }

But still getting "Errore! 500 - Internal Server Error", but no error debugging server code, I can see in result value [{"ID":1,"campo1":null,"campoData":"/Date(1410166675790)/","campoInt":3858.62},{"ID":2,"campo1":null,"campoData":"/Date(1410166675790)/","campoInt":3858.62} (...)].
If I comment the Response.End() (just to try) I'm getting "Errore! 200 - OK"

UPDATE 2:

OK, I've installed Fiddler, and the error 500 is actually referring to the ThreadAbortException that's coming with the Response.End(). Coming back to the original code with the method returning the List there's the real problem... Exception message: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

UPDATE 3:

OK, I've seen this: Ajax request returns 200 OK, but an error event is fired instead of success and this: jQuery AJAX status "200 OK", but no data response on why I'm getting OK but not success commenting the Response.End().. I don't know if I can put the entire list in a JSON also setting the maxJsonLength to Int32.MaxValue, because is actually a List of 2437 elements with a lot of fields..

Community
  • 1
  • 1
MisterFrank
  • 177
  • 1
  • 4
  • 21
  • I've always returned JSON from my Web Services, never tried a List<> before. I found this: http://www.dotnetcurry.com/showarticle.aspx?ID=320 – Rick S Oct 27 '14 at 14:44
  • WebMethod is deprecated by Microsoft. You should look into [ASP.NET Web API](http://www.asp.net/web-api). It's better supported, easier to work with, and cleaner. – mason Oct 27 '14 at 14:55
  • They use Framework 3.5 at work, so no Web API.. Now I'm trying to use JavaScriptSerializer.. – MisterFrank Oct 27 '14 at 15:07
  • @Rick S I've seen only now that you have posted a link with your comment! Probably It's exactly that the problem, because I've the same weird date, but cannot install plugin at work.. – MisterFrank Oct 27 '14 at 16:06
  • No, this guy have the same date problem, but it's only a format problem, he's not getting error 500... http://stackoverflow.com/questions/206384/how-to-format-a-microsoft-json-date – MisterFrank Oct 27 '14 at 16:10
  • 1
    You need to download and use [Fiddler2](http://www.telerik.com/fiddler). It will tell you the details of the 500 error you're getting. – Icemanind Oct 27 '14 at 16:18
  • The `ThreadAbortException` should be ignored. That's called on every `Response.End`. Also, you should replace `throw ex;` with just `throw;` so you don't lose the original stack trace. – mason Oct 27 '14 at 16:48
  • @mason I know, and the same for Response.Redirect, in fact I usually use an if (!(ex is ThreadAbortException)) to don't have a dirty log file, but how I could let Ajax call ignoring it? Because I could use jSearializer.MaxJsonLength = Int32.MaxValue; for the other problem.. I prefer do not have to set it by Web.Config.. Why if I comment the Response.End I'm getting "200 - OK" but not success? – MisterFrank Oct 27 '14 at 17:06
  • @MisterFrank The response should end, and so the only thing written to the response should be the JSON. You might try also setting `HttpContext.Current.Response.StatusCode = 400;` before the `Response.End()` call. – mason Oct 27 '14 at 17:17
  • @mason Tried the StatusCode, but same problem. Coming back to the old WebMethod returning directly the List it show the maxJsonLength property error on JavaScriptSerializer, so he's probably trying to do the same (serialize the list and write it to the Response) automatically.. I think the problem is finally the current List is too big for a JSON file.. – MisterFrank Oct 27 '14 at 17:30
  • Try using JSON.NET. That may get around your size limitation. – mason Oct 27 '14 at 17:35

2 Answers2

0

What I've found when using WebMethod is that sometimes it's necessary to force it to return JSON. You lose content negotiation (unless you manually implement it). And I still recommend switching to Web API if it all possible. But this should do the trick.

[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();
}

So you switch it to void for the return type. Then you set the content type of the response to be JSON. Then manually convert your "return object" to JSON and write it to the response, then end the response.

mason
  • 31,774
  • 10
  • 77
  • 121
0

Setting this in Web.Config:

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

founded on this:

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

Now it's working with the original WebMethod.

Community
  • 1
  • 1
MisterFrank
  • 177
  • 1
  • 4
  • 21