ASMX Web Service - Return user defined class with properties

隐身守侯 提交于 2020-01-13 03:19:12

问题


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:


  1. private properties are not sent to the client if I remember right.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!