我们过去使用 WCF over ASP.NET,最近切换到 WCF over ASP.NET Core。这很难实现,因为 ASP.Net Core 不支持开箱即用的 WCF。一方面,整个 web.config XML 配置模型已转储到 ASP.NET Core 中,因此我们无法在那里配置 WCF 跟踪。
即这个文件没用: https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/configuring-tracing
我们不得不通过在 WCF 和端口 80 之间放置一个 http 代理来破解 ASP.NET Core。WCF 实际上在另一个端口上运行。
问题是,如果 ASP.NET Core 不关注 web.config,我们如何启用 WCF 跟踪?
最佳答案
在客户端跟踪的情况下,我使用自定义端点行为 (IEndpointBehavior
) 和自定义消息日志检查器 (IClientMessageInspector
) 来获取输入和输出消息。
客户端初始化:
_serviceClient = new MyCustomServiceClient();
_serviceClient.Endpoint.Address = new System.ServiceModel.EndpointAddress(_configParams.ServiceUri);
_serviceClient.Endpoint.EndpointBehaviors.Add(new EndpointLoggingBehavior("MyCustomService"));
EndpointLoggingBehavior
的实现:
public class EndpointLoggingBehavior : IEndpointBehavior
{
public EndpointLoggingBehavior(string serviceName)
{
_serviceName = serviceName;
}
private readonly string _serviceName;
public void AddBindingParameters(ServiceEndpoint endpoint,
System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new MessageLoggingInspector(_serviceName));
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
MessageLoggingInspector
的实现:
public class MessageLoggingInspector : IClientMessageInspector
{
private readonly string _serviceName;
public MessageLoggingInspector(string serviceName)
{
_serviceName = serviceName;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
// copying message to buffer to avoid accidental corruption
var buffer = reply.CreateBufferedCopy(int.MaxValue);
reply = buffer.CreateMessage();
// creating copy
var copy = buffer.CreateMessage();
//getting full input message
var fullInputMessage = copy.ToString();
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// copying message to buffer to avoid accidental corruption
var buffer = request.CreateBufferedCopy(int.MaxValue);
request = buffer.CreateMessage();
// creating copy
var copy = buffer.CreateMessage();
//getting full output message
var fullOutputMessage = copy.ToString();
return null;
}
}
然后,当然,您需要将这些消息写入任何存储。
关于c# - ASP.NET Core 中的 WCF 跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52090368/