gpt4 book ai didi

C#.NET WebService 返回对象

转载 作者:行者123 更新时间:2023-11-30 21:23:43 24 4
gpt4 key购买 nike

我正在使用 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; }
}

网络服务示例方法

    [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;
}

我使用两种客户端类型,javascript 和 C#.NET Windows Form。当我从 javascript 调用时,我没有遇到任何问题,并且 osr.data 中充满了 WS_User。所以我可以轻松使用 osr.data.id。但是当我从 C#.NET 使用时(代理是使用“添加 Web 引用”生成的)我可以成功调用但是当结果到达时我得到一个 Soap 异常

{System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.InvalidOperationException: There was an error generating the XML document. ... ...

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

谢谢

马苏德

添加:

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

    [WebMethod]
public WS_User Dummy()
{
return new WS_User();
}

最佳答案

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

[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;
}
}
}

我认为你应该这样修改你的代码:

[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; }
}

关于C#.NET WebService 返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1599063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com