有道过WCF抛出异常抛出、异常、WCF

2023-09-03 01:01:59 作者:主宰稳场

我想通过WCF中可能是最通用的方式发送例外。以下是我有:

I'm trying to send exceptions over WCF in the most generic way possible. Here's what I've got:

[ServiceContract]
interface IContract
{
    [OperationContract]
    void Foo();
}

class ContractImplementation: IContract
{
    public void Foo()
    {
        try
        {
            Bar();
        }
        catch (Exception ex)
        {
            throw new FaultException<Exception>(ex, ex.Message);
        }
    }
}

这实际上是走出酒吧的例外是:

The exception that is actually coming out of Bar is:

[Serializable]
class MyException : Exception
{
    // serialization constructors
}

我看到在服务器端的WCF日志记录的错误是:

The error I'm seeing in the server-side WCF logging is:

输入MyException数据   合约名称   MyException: http://schemas.datacontract.org/2004/07/MyException   预计不会。考虑使用DataContractResolver或添加任何   不已知类型静态已知类型的列表 - 例如,   通过使用KnownTypeAttribute属性或通过将其添加到   已知类型的列表传递给DataContractSerializer的

Type 'MyException' with data contract name 'MyException:http://schemas.datacontract.org/2004/07/MyException' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

我试过到目前为止:

[ServiceKnownType(typeof(MyException))]
[ServiceContract]
interface IContract
{
    [FaultContract(typeof(MyException))]
    [OperationContract]
    void Foo();
}

但没有运气。

But no luck.

推荐答案

首先,在MyException,从异常删除的继承,使之公开。

First, in MyException, remove the inheritance from Exception and make it public.

二,当你声明你的服务合同,宣布例外,因为它如下:

Second, when you declare your service contract, declare exception as it follows:

[FaultContractAttribute(
        typeof(MyException),
        Action = "", 
        Name = "MyException", 
        Namespace = "YourNamespace")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults = true)]
    [OperationContract]
    void Foo()

最后,你可以把你的例外是这样的:

Finally, you can throw your Exception like this:

throw new FaultException<MyException>
             (
                 new MyException(ex.Message),
                 new FaultReason("Description of your Fault")

             );

希望它帮助。

Hope it helps.

 
精彩推荐