问题
Hey, I am trying to return a user defined class from a web method. The class has properties and/or methods. Given the following web method:
[WebMethod]
public List<MenuItem> GetMenu()
{
List<MenuItem> menuItemList = new List<MenuItem>();
menuItemList.Add(new MenuItem());
menuItemList.Add(new MenuItem());
menuItemList.Add(new MenuItem());
return menuItemList;
}
Now, suppose this web service is consumed by adding a web reference in a newly created console application. The following code is used to test it:
public void TestGetMenu()
{
MenuService service = new MenuService.MenuService();
service.MenuItem[] menuItemList = service.GetMenu();
for (int i = 0; i < menuItemList.Length; i++)
{
Console.WriteLine(menuItemList[i].name);
}
Console.ReadKey();
}
First of all, this doesn't work if the MenuItem class contains properties... Also, if the MenuItem class contains a method the call to the web method doesn't fail, but the method is not in the generated proxy class.. for example: menuItemList[i].getName() does not exist. Why? What am i missing?
//This works
public class MenuItem
{
public string name;
public MenuItem()
{
name = "pizza";
}
}
//This crashes / doesnt work
public class MenuItem
{
private string name;
public MenuItem()
{
name = "pizza";
}
public string Name
{
get { return name; }
set { name = value; }
}
}
//This successfully calls web method, but the method does not exist during test
public class MenuItem
{
private string name;
public MenuItem()
{
name = "pizza";
}
public string getName()
{
return name;
}
}
回答1:
It will only work if the class is serializable which usually means public fields and properties, this is why your MenuItem will fail because your client
side has no idea how to construct the MenuItem class properly.
Try this:
[Serializable]
public class MenuItem
{
private string name;
public MenuItem()
{
name = "pizza";
}
public string Name
{
get {
return name;
}
set {
name = value;
}
}
}
回答2:
- private properties are not sent to the client if I remember right.
- Methods cannot be generated on the client. What is a method used some resources on the server? 2a. To work around this, you can use partial classes to reimplement some of the methods.
来源:https://stackoverflow.com/questions/3839637/asmx-web-service-return-user-defined-class-with-properties