【问题标题】:How to get type(as in request.GetType) of a request message in Service Behavior of WCF Service如何在 WCF 服务的服务行为中获取请求消息的类型(如 request.GetType)
【发布时间】:2014-03-24 22:28:35
【问题描述】:

我正在编写一个自定义 ServiceBehavior,它希望我知道请求消息的类型,以推断该消息是否使用自定义属性装饰。

我的示例合同可能如下所示:

    [DataContract]
[Auditable]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    [Audit]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    [Audit]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

我正在尝试通过使用来识别行为方面的自定义属性:

public object AfterReceiveRequest(ref Message request, IClientChannel channel,
    InstanceContext instanceContext)
{
    var typeOfRequest = request.GetType();

    if (!typeOfRequest.GetCustomAttributes(typeof (AuditableAttribute), false).Any())
    {
        return null;
    }
}

但是 typeOfRequest 总是作为 {Name = "BufferedMessage" FullName = "System.ServiceModel.Channels.BufferedMessage"}

有没有一种方法可以通过使用请求来推断消息的类型?

注意:我直接引用了包含合同的程序集,并且服务不是通过 wsdl 引用的。

【问题讨论】:

  • 您的服务使用 SOAP 吗?
  • 是的,它使用 SOAP 消息进行通信。
  • 您可以检查 SOAP 消息以确定在请求中序列化了哪些对象。但是为什么要在消息被服务反序列化之前确定消息中定义的类型呢?
  • 如问题陈述中所述,我只想读取由自定义属性修饰的合同的某些值。

标签: c# wcf servicebehavior idispatchmessageinspector


【解决方案1】:

上述问题的解决方案是不使用MessageInspector(如IDispatchMessageInspectorIClientMessageInspector),而是使用参数Inspector(如IParameterInspector i>)。

在 BeforeCall 方法中,我们可以这样做:

public object BeforeCall(string operationName, object[] inputs)
{

        var request = inputs[0];

        var typeOfRequest = request.GetType();

        if (!typeOfRequest.GetCustomAttributes(typeof(CustomAttribute), false).Any())
        {
            return null;
        }
}

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多