I have a followup question to this question.
I’m writing a web service which dynamically calls other web services, using the WSProxy class found here.
Using WSProxy returns an object with a dynamic type, depending on the web service method called. For example, if I’m calling a method that returns…
<StateCodes>
<StateCode>
<Code>AL</Code>
<Name>Alabama</Name>
</StateCode>
<!-- and so on -->
</StateCodes>
then the object is of the type StateCodes[].
If I’m calling a method that returns …
<GetVehicleMakes>
<VehicleMakes>
<Vehicle_Make_Code>00</Vehicle_Make_Code>
<Vehicle_Make_Description>Ford</Vehicle_Make_Description>
</VehicleMakes>
<VehicleMakes>
<Vehicle_Make_Code>01</Vehicle_Make_Code>
<Vehicle_Make_Description>Toyota</Vehicle_Make_Description>
</VehicleMakes>
<!-- and so on -->
</GetVehicleMakes>
then the object is of the type GetVehicleMakes[].
I can’t declare a class type beforehand because the class type of the returned object is determined by the web service method called, and the web service method is determined at runtime. There are dozens of methods with different return types on the local service I’m testing against. I don’t get to know the type of the returned object before runtime, because any method from any web service could be called.
When I try to return the object straight up, like so:
[WebMethod]
public object RunService(string webServiceAsmxUrl, string serviceName, string methodName, string jsonArgs)
{
WSDLRuntime.WsProxy wsp = new WSDLRuntime.WsProxy();
// Convert JSON to C# object.
JavaScriptSerializer jser = new JavaScriptSerializer();
var dict = jser.Deserialize<Dictionary<string,object>>(jsonArgs);
object result = wsp.CallWebService(webServiceAsmxUrl, serviceName, methodName, dict);
// This line produces the error.
return result;
}
I can insert a breakpoint at the return result line, and browse my result object. For example, when I call the StateCodes method, the result variable is the StateCodes[] array.
However, once return result runs, the XML parser won’t have it.
System.InvalidOperationException: The type StateCodes[] may not be used in this context.
I’ve searched for answers, and I see terms like, “reflection” and “serialization” coming up, but I am very new to C# and don’t know if these are what I want or how they work.
I’m using C# 3.5.
It looks like you need to return the xml that is returned from the service call. You can’t return the object directly because the top-level service (the one that has a return type of object) is not generated at runtime; it is defined when its wsdl is consumed.
Long story short, you should change the return type of your top-level WebMethod to be string and serialize
resultmanually in order to do what you want. Then the client (who presumably knows what they expect to get back from the service that they are requesting viawebServiceAsmxUrl,serviceName, andmethodName) can deserialize the result themselves.