我對上一個答案表示歉意,我愚蠢地認爲我只是投了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) {
//Do nothing
}
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。我有一個微弱的回憶,它總是空的,這個討厭的過程是我能得到一個實際包含有效數據的實例的唯一途徑。
我覺得不涉及
嗨達雷爾, 我試過你的建議,遇到了一些問題。 當我使用你的確切代碼,我得到了這個錯誤(在編譯時): 無法將類型'System.ServiceModel.Web.WebOperationContext'轉換爲'System.ServiceModel.OperationContext' 當我將其更改爲此代碼時: string body = OperationContext.Current.RequestContext.RequestMessage.ToString(); 機體在運行時爲空字符串。 任何想法? 謝謝, Uri – urini 2009-09-08 10:37:20