3

I have the following web service:

[ScriptService]
public class Handler : WebService {

    [WebMethod]
    public void method1() {

        string json = "{ \"success\": true }";

        System.Web.HttpContext.Current.Response.Write(json);

    }

    [WebMethod]
    public object method2(Dictionary<string, object> d) {

        Dictionary<string, object> response = new Dictionary<string, object>();

        response.Add("success", true);

        return response;

    }

}

The first method accepts a traditional html form post and response writes a JSON string to the page. The second method accepts a JSON value posted via AJAX and returns a serialized object.

Both these methods work fine on their own but when put together in the same web service I get this error when calling method1:

System.IndexOutOfRangeException: Index was outside the bounds of the array.

When I remove the arguments from method2 they work.

Can anyone suggest why this is happening?

Edit:

The problem spans from the argument type of method2. If I change it to a string or simple data type it works fine. As Joel suggests it's probably because Dictionaries can't be serialized. This doesn't seem to affect my requests sent by ajax and only breaks direct form posts to this handler. Therefore my workaround is to put the form post handlers in a separate file by themselves. Not ideal but works for my application.

Mark Clancy
  • 7,831
  • 8
  • 43
  • 49

1 Answers1

4

Dictionaries are not serializable. Hiding it behind an object doesn't do anything for you. You must first convert your dictionary to an array or some other serializable object before sending it out.

Why isn't there an XML-serializable dictionary in .NET? http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx http://www.tanguay.info/web/index.php?pg=codeExamples&id=333

Community
  • 1
  • 1
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
  • Thanks for the reply, I've always returned json this way and it seems to work fine as long as the objects in the dictionary are serializable. I'm not sure if this is the reason behind the above problem. – Mark Clancy Dec 15 '10 at 11:43
  • @CL4NCY - As a test, change the return type and your objects to `List` and see if it throws up an error. If it's not the dictionary, you should get the same error. – Joel Etherton Dec 15 '10 at 11:46
  • The return type doesn't seem to affect the error but the arguments for method2 do. If I remove them or change them to 'string d' instead of 'Dictionary d' then it works. I don't understand how method2 can affect calling method1. – Mark Clancy Dec 15 '10 at 11:54