我有一个WCF服务,它将JSON返回给客户端。
这是app.config
<system.serviceModel>
<services>
<service name="MyServices.MyService">
<endpoint address="" behaviorConfiguration="JsonBehavior" binding="webHttpBinding"
contract="Myervices.IMyervice">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/MyEmulator/Service1/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="JsonBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
这是服务公开的示例操作
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, Method = "GET", UriTemplate = "me/{id}")]
JsonObject GetObject(string id, string connection_type);
现在,我想记录服务从客户端收到的每个请求以及正在发送回客户端的响应......在这种情况下,它会犯罪JSOn。
我创建了一个自定义MessageInspector,如下所示
public class MyMessageInspector : IDispatchMessageInspector
{
private bool LoggingEnabled;
#region IDispatchMessageInspector Members
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
Guid correlationState = Guid.NewGuid();
if (this.LoggingEnabled)
{
StringBuilder message = new StringBuilder();
message.AppendFormat("CorrelationState = {0}{1}", correlationState, Environment.NewLine);
message.AppendFormat("Local Address = {0}{1}", channel.LocalAddress, Environment.NewLine);
message.AppendFormat("Remote Address = {0}{1}", channel.RemoteAddress, Environment.NewLine);
message.AppendLine("Request");
message.AppendLine(request.ToString());
message.AppendLine();
this.logger.LogMessage(message.ToString());
}
return correlationState;
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
if (this.LoggingEnabled)
{
StringBuilder message = new StringBuilder();
message.AppendFormat("CorrelationState = {0}{1}", correlationState, Environment.NewLine);
message.AppendLine("Reply");
message.AppendLine(reply.ToString());
message.AppendLine();
this.logger.LogMessage(message.ToString());
}
}
#endregion
}
但这似乎没有记录任何resposne .. response.Tostring()只说“... stream”
如果我的服务以SOAP XML格式返回数据,则上述工作正常...但是我希望它在我调用REST服务端点时记录JSON响应,这是在浏览器中下载的* .js文件中的文本。例如:http://localhost:8080/MyService/me/2/
我是如何实现这一目标的?
答案 0 :(得分:5)
此代码提供了一种处理REST消息的机制,并且作为奖励允许SOAP正常传递。它有点干扰(通过读取来破坏流,因此代码需要重新生成它)但我还没有找到更好的方法。
http://code.msdn.microsoft.com/WCF-REST-Message-Inspector-c4b6790b