【问题标题】:How to get access to inherited object properties in WCF?如何访问 WCF 中继承的对象属性?
【发布时间】:2011-10-28 15:29:08
【问题描述】:

案例是:

[ServiceContract]
public interface IInfo
{
    [DataMember]
    int Id{get;set;}
}

[DataContract]
[KnownType(typeof(Legal))]
public class Info
{
    [DataMember]
    public int Id { get; set; }
}

[DataContract]
public class Legal : Info
{
    [DataMember]
    public string ManagerName { get; set; }
}

[ServiceContract]
[ServiceKnownType(typeof(Legal))]
public interface IMyService
{
    [OperationContract]
    int DoWork(Info dto);
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{

    public int DoWork(Info dto)
    {
        string name;
        if (dto is Legal)
            name = (dto as Legal).ManagerName;
        return dto.Id;
    }
}

是否可以将 dto 知道为 Legal 类型并可以访问子属性?

我想存储 dto,我不想为每个 info 子项提供很多服务。

将泛型传递给服务不起作用,wsdl 错误, IInfo 等接口作为输入参数不起作用,转换错误, 像 Info 这样的基类不起作用,子道具无法访问, 堆栈溢出不起作用,这是我第二次发布此问题但没有答案!

【问题讨论】:

  • 无论您在 WCFHost-Tool 中遇到的错误如何,您都尝试托管服务吗?在一些复杂的场景中,这个工具对你“撒谎”。例如,如果将其部署到 IIS,一切正常。我会尽快试用您的样品!敬请期待。
  • 试用了您的样品。这个对我有用。您的示例代码是否有效并且您不想做其他事情?您能否发布一个不适合您的示例?
  • 那是我的确切样本伙计!我很快就会在iis上试用它,tnx的建议。有邮件地址吗?
  • 在 IIS 上不起作用。错误是:无法将“System.Object”类型的对象转换为“WebApplication.Dtos.IInfo”我的示例代码完全粘贴在上面。
  • 我看不出您的 IInfo 接口的意义,它从未使用过(未由 Info 实现或由 DoWork 声明),此外,它具有 ServiceContract 属性,但包含具有 DataMember 的成员属性,这不合适。

标签: c# .net wcf inheritance


【解决方案1】:

我将 json 作为 dto 传递给 MyService。 如果我添加“__type”:“Legal:#Dto”,MyService 将 dto 识别为 Legal。 然后 (dto as Legal).ManagerName 具有价值

这个解决方案有效,实际上传递 __type 不是很方便的方法。我会感谢您提出更好的建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2018-07-11
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    相关资源
    最近更新 更多