对于之前的回答,我深感抱歉。我愚蠢地认为只需将WebOperationContext转换为OperationContext即可,但实际上答案要复杂得多。
首先,让我先说一下,肯定有更好的方法!
首先,我创建了自己的上下文对象,可以附加到现有的OperationContext对象上。
public class TMRequestContext : IExtension<OperationContext> {
private OperationContext _Owner;
public void Attach(OperationContext owner) {
_Owner = owner;
}
public void Detach(OperationContext owner) {
_Owner = null;
}
public static TMRequestContext Current {
get {
if (OperationContext.Current != null) {
return OperationContext.Current.Extensions.Find<TMRequestContext>();
} else {
return null;
}
}
}
}
为了能够访问这个新的上下文对象,您需要将其作为当前对象的扩展添加进去。我通过创建一个消息检查器类来实现这一点。
public class TMMessageInspector : IDispatchMessageInspector {
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) {
OperationContext.Current.Extensions.Add(new TMRequestContext());
return null;
}
}
为了让消息检查器起作用,您需要创建一个新的“行为”。我使用以下代码来完成这个操作。
public class TMServerBehavior : IServiceBehavior {
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) {
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) {
foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers) {
foreach (EndpointDispatcher epDisp in chDisp.Endpoints) {
epDisp.DispatchRuntime.MessageInspectors.Add(new TMMessageInspector());
}
}
}
}
你应该能够在配置文件中添加行为,尽管我是通过创建新主机并在 OnOpening 方法中手动添加行为对象来实现的。我最终使用这些类不仅仅是访问 OperationContext 对象,还用于日志记录、重写错误处理和访问 HTTP 请求对象等。因此,它并不像看起来那么荒谬。几乎是,但不完全是!
我真的不记得为什么不能直接访问 OperationContext.Current。我模糊地记得它总是为空,而这个麻烦的过程是我能够获取包含有效数据的实例的唯一方式。
BodyStyle
默认为WebMessageBodyStyle.Bare
。 - Ε Г И І И О