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



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

为了进一步说明这个问题:

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

[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?
}

我的完整解决方案是这样的,它可以毫无问题地工作:
1。首先获取此处讨论的操作说明
2。然后查找"服务中的操作"上设置的自定义属性接口:

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;
}
}

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

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;
}
}

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

相关内容

  • 没有找到相关文章

最新更新