C#.NET WebService 返回对象

max*_*max 3 c# web-services

我正在使用 ASP.NET C# 创建一个 Web 服务。我从网络服务发送各种数据类型,所以我使用以下结构。

public enum WS_ServiceResponseResult
{
    Success,
    Failure,
}
public class WS_ServiceResponse
{
    public WS_ServiceResponseResult result { get; set; }
    public object data { get; set; }
}

public class WS_User
{
    public long id{ get; set; }
    public string name{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)

网络服务示例方法

    [WebMethod(EnableSession = true)]
    public WS_ServiceResponse LogIn(string username, string pasword)
    {
        WS_ServiceResponse osr = new WS_ServiceResponse();
        long userID = UserController.checkLogin(username, pasword);

        if (userID != 0)
        {
            osr.result = WS_ServiceResponseResult.Success;
            osr.data = new WS_User() { id = userID, name = username };
        }
        else
        {
            osr.result = WS_ServiceResponseResult.Failure;
            osr.data = "Invalid username/password!";
        }
        return osr;
    }
Run Code Online (Sandbox Code Playgroud)

我使用两种客户端类型,javascript 和 C#.NET Windows 窗体。当我从 javascript 调用时,我没有问题,并且 osr.data 充满了 WS_User。所以我可以很容易地使用 osr.data.id。但是当我从 C#.NET 使用时(代理是使用“添加 Web 引用”生成的)我可以成功调用但是当结果到达时我得到一个 Soap Exception

{System.Web.Services.Protocols.SoapException:System.Web.Services.Protocols.SoapException:服务器无法处理请求。---> System.InvalidOperationException: 生成 XML 文档时出错。……

我错过了什么?我猜对象没有明确定义并导致问题。有哪些解决方法?

谢谢

马克苏德

添加:

如果添加以下虚拟方法,则效果很好。希望它有所帮助,以获得解决方案。

    [WebMethod]
    public WS_User Dummy()
    {
        return new WS_User();
    }
Run Code Online (Sandbox Code Playgroud)

Art*_*hur 5

我有一个类似的问题,返回一个“对象”(可能有多个类)这是一个示例代码:

[Serializable()]
[XmlRoot(ElementName="Object")]
public sealed class XMLObject
{

    private Object _Object;

    [XmlElement(Type=typeof(App.Projekte.Projekt), ElementName="Projekt")]
    [XmlElement(Type=typeof(App.Projekte.Task), ElementName="Task")]
    [XmlElement(Type=typeof(App.Projekte.Mitarbeiter), ElementName="Mitarbeiter")]
    public Object Object
    {
        get
        {
            return _Object;
        }
        set
        {
            _Object = value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为您应该以这种方式更改代码:

[XmlRoot(ElementName="ServiceResponse")]
public class WS_ServiceResponse
{
    public WS_ServiceResponseResult result { get; set; }

    [XmlElement(Type=typeof(WS_User), ElementName="WS_User")]
    [XmlElement(Type=typeof(string), ElementName="Text")]
    public object data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)