如何使用IDispatchMessageInspector获取WCF合同操作的自定义属性值

时间:2014-01-03 06:32:28

标签: c# wcf idispatchmessageinspector

问题在于AfterReceiveRequest如何使用OperationDescription查找Operation上的自定义属性集?如果有办法,最好在服务合同接口或服务实现类中的操作声明上设置自定义属性吗?

进一步说明问题:

public interface IGetterSetterService
{
    [OperationContract, GetterRequest]
    Data[] GetData();
    [OperationContract, SetterRequest]
    bool SetData(string Data);
}

OR

[WebInvoke(Method = "*", ResponseFormat = WebMessageFormat.Json, UriTemplate = "xyz"]
[GetterRequest]
public Data[] GetData()
{
    return new Data[];
}
[WebInvoke(Method = "*", ResponseFormat = WebMessageformat.Json, UriTemplate = "xyz/{data}"]
[SetterRequest]
public bool SetData(string data)
{
    return true;
}

现在是IDispatchMessageInspector:

public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
    //Here how to find out the GetterRequest or SetterRequest custom attribute set on an
    //operation, may be using OperationDescription for the current context?
}

2 个答案:

答案 0 :(得分:1)

我的完整解决方案看起来像这样,它的工作没有任何问题:
 1.首先获得所讨论的操作说明here
 2.然后找到在Service in Operations中设置的自定义属性     接口:

private UserAction GetIntendedUserAction(OperationDescription opDesc)
{
    Type contractType = opDesc.DeclaringContract.ContractType;
    var attr = contractType.GetMethod(opDesc.Name).GeCustomAttributes(typeof(RequestedAction), false) as RequestedAction[];
    if (attr != null && attr.Length > 0)
    {
        return attr[0].ActionName;
    }
    else
    {
        return UserAction.Unknown;
    }
}
public enum UserAction
{
    Unknown = 0,
    View = 1,
    Control = 2,
    SysAdmin = 3,
}
[AttributeUsage(AttributeTargets.Method)]
public class RequestedAction : Attribute
{
    public UserAction ActionName { get; set; }
    public RequestedAction(UserAction action)
    {
        ActionName = action;
    }
}

答案 1 :(得分:0)

我认为您可以使用此代码:

public class operationdispatcher : IDispatchMessageInspector
{
    List<Type> MyAttrybutes = new List<Type>() { typeof(behaviorattribute) };

    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        var serviceType = instanceContext.Host.Description.ServiceType;
        var operationName = OperationContext.Current.IncomingMessageHeaders.Action;
        var methodName = operationName.Substring(operationName.LastIndexOf("/") + 1);

        var method = serviceType.GetMethods().Where(m => m.Name == methodName && m.IsPublic).SingleOrDefault();
        var attributes = method.GetCustomAttributes(true).Where(a => MyAttrybutes.Contains(a.GetType()));

        foreach (var attribute in attributes)
        {
            // you might want to instantiate an attribute and do something
        }

        return null;
    }
}

注意:您在这里使用服务实现类,而不是接口。如果使用method.GetCustomAttributes(true),那么您将获得指定方法的所有自定义属性(从接口继承的那些)。