WCF: Same Faultcontract on many methods

浪子不回头ぞ 提交于 2019-12-04 23:50:27

No, you need to do it on each and every method - WCF is rather picky and requires explicit settings pretty much for everything (which really is a good thing in the end, I am convinced).

Marc

cocogza

You can do it by creating a custom attribute.

Implement IContractBehavior and add the fault to each operation on the Validate method.

void IContractBehavior.Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
   foreach (OperationDescription od in contractDescription.Operations)
      od.Add(yourFault);
}

Here's a link that details how to achieve this. Below the actual code to use:

[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]
public class StandardFaultsAttribute : Attribute, IContractBehavior
{
    // this is a list of our standard fault detail classes.
    static Type[] Faults = new Type[]
    {
        typeof(AuthFailure),
        typeof(UnexpectedException),
        typeof(UserFriendlyError)
    };

    public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
    }

    public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
    {
    }

    public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
    {
        foreach (OperationDescription op in contractDescription.Operations)
        {
            foreach (Type fault in Faults)
            {
                op.Faults.Add(MakeFault(fault));
            }
        }
    }

    private FaultDescription MakeFault(Type detailType)
    {
        string action = detailType.Name;
        DescriptionAttribute description = (DescriptionAttribute)                Attribute.GetCustomAttribute(detailType, typeof(DescriptionAttribute));

        if (description != null)
            action = description.Description;
        FaultDescription fd = new FaultDescription(action);
        fd.DetailType = detailType;
        fd.Name = detailType.Name;
        return fd;
    }
}

Yes on each operation contract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!