【问题标题】:How to force wcf service to serialize a class如何强制 wcf 服务序列化一个类
【发布时间】:2017-01-26 11:19:07
【问题描述】:

我正在创建 WCF 服务并通过抛出 WebFaultException<MyResultClass> 来处理错误。 (MyResultClass) 是我项目中的一个类:

[DataContract]
    public class MyResultClass
    {
        [DataMember(IsRequired = false)]
        public int Code;
        [DataMember(IsRequired = false)]
        public string Description;
        public MyResultClass()
        {

        }

    }

问题是 WCF 服务没有序列化这个类。

【问题讨论】:

标签: c# rest wcf


【解决方案1】:

首先(正如其他人提到的)你应该使用属性。

[DataContract]
public class MyResultClass
{
    [DataMember]
    public int Code { set; get; }
    [DataMember]
    public string Description { set; get; }
}

此外,您需要在界面中指定FaultContract。否则客户不知道会发生什么。由于WebFaultException 继承自FaultException,因此无需指定。

[ServiceContract]
public interface IService:
{
    [OperationContract]
    [FaultContract(typeof(MyResultClass))]
    void DoStuff();
}

你的实现:

public class Service : IService
{
    public void DoStuff()
    {
        var detail = new MyResultClass
        {
            Code = 400,
            Description = "foo"
        };
        throw new WebFaultException<MyResultClass>(detail, HttpStatusCode.BadRequest);
    }
}

还有你的客户:

try
{
    // Call your WCF service here...
}
catch (FaultException<MyResultClass> e)
{
    MyResultClass detail = e.Detail;
    // Do stuff with detail
}
catch (Exception e)
{
    // Some other error
}

【讨论】:

  • 谢谢。你是一个救生员:)
【解决方案2】:

请将您的课程改为这个并尝试:

[DataContract]
public class MyResultClass
{
    [DataMember]
    public int Code { set; get; }
    [DataMember]
    public string Description { set; get; }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多