We used to use WCF over ASP.NET and recently switched to WCF over ASP.NET Core. This was quite hard to implement because ASP.Net Core doesn't support WCF out of the box. For one thing, the whole web.config XML configuration model has been dumped in ASP.NET Core so we cannot configure WCF tracing there.
I.e. this document is useless:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/configuring-tracing
We had to hack ASP.NET Core by putting a http proxy between WCF and port 80. WCF is actually running on another port.
The question is, how do we enable WCF tracing if ASP.NET Core doesn't pay attention to the web.config?
In case of client side tracing I used custom endpoint behaviour (IEndpointBehavior) with custom message logging inspector (IClientMessageInspector) to get input and output messages.
Client initialization:
_serviceClient = new MyCustomServiceClient();
_serviceClient.Endpoint.Address = new System.ServiceModel.EndpointAddress(_configParams.ServiceUri);
_serviceClient.Endpoint.EndpointBehaviors.Add(new EndpointLoggingBehavior("MyCustomService"));
Implementation of 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)
{
}
}
Implementation of 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;
}
}
Then, of course, you will need to write these messages to any storage.
You'll use ETW Tracing for WCF on .NET Core
https://github.com/dotnet/wcf/blob/master/Documentation/HowToUseETW.md
In my experience, you have some limitations
Tracing is on for All WCF Apps, rather than configuring for a single app through config file
You cannot output Messages with ETW tracing
SvcTraceViewer.exe doesn't work well for trace review, you'll need to move to PerfView.exe which may present a learning curve
Benefits of ETW
You avoid the performance hit from classic forms of tracing
No more config change to start/stop tracing
Building on the excellent answer by Petr Pokrovskiy, this is how you can redirect the trace to the standard .NET Core log:
Client initialization:
ILogger<MyCustomService> = ...; // use dependency injection to get instance
_serviceClient = new MyCustomServiceClient();
_serviceClient.Endpoint.Address = new System.ServiceModel.EndpointAddress(_configParams.ServiceUri);
_serviceClient.Endpoint.SetTraceLogging(logger);
Implementation of SetTraceLogging:
using Microsoft.Extensions.Logging;
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
namespace Common.ServiceModel.Logging
{
public static class ServiceEndpointExtensions
{
public static void SetTraceLogging(this ServiceEndpoint serviceEndpoint, ILogger logger)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
if (logger.IsEnabled(LogLevel.Trace))
serviceEndpoint.EndpointBehaviors.Add(new ClientMessageLoggingBehavior(logger));
}
}
internal sealed class ClientMessageLoggingBehavior :
IEndpointBehavior
{
private readonly ILogger _logger;
public ClientMessageLoggingBehavior(ILogger logger)
{
_logger = logger;
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new ClientMessageLogger(_logger));
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
internal sealed class ClientMessageLogger :
IClientMessageInspector
{
private readonly ILogger _logger;
public ClientMessageLogger(ILogger logger)
{
this._logger = logger;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
// copying message to buffer to avoid accidental corruption
reply = Clone(reply);
this._logger.LogTrace("Received SOAP reply:\r\n{0}", reply.ToString());
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// copying message to buffer to avoid accidental corruption
request = Clone(request);
this._logger.LogTrace("Sending SOAP request:\r\n{0}", request.ToString());
return null;
}
private static Message Clone(Message message)
{
return message.CreateBufferedCopy(int.MaxValue).CreateMessage();
}
}
}
Related
I am stuck with a call to soap service which needs "enveloped-signature" as transform algorithm. And i am getting "xml-exc-c14n#". I am using custom binding to initialize the client for WCF request.
Update:
In the above example, I was trying without Message Inspectors. So I have tried both ways. 1. using WCF call but then I am unable to change the transform algorithm to "enveloped-signature". 2. I tried using Inspector where I try to create signed XML document and add this to the request message. Like explained in this example Message inspectors- WCF call
I failed in both.
Below is the code i am using for WCF call without Inspector
var b = new CustomBinding();
var sec = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10);
sec.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());
sec.MessageSecurityVersion =
MessageSecurityVersion.
WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12;
sec.IncludeTimestamp = false;
sec.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt;
sec.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256Sha256;
X509SecurityTokenParameters x509Params = new X509SecurityTokenParameters
{
X509ReferenceStyle = X509KeyIdentifierClauseType.IssuerSerial,
RequireDerivedKeys = false,
InclusionMode = SecurityTokenInclusionMode.Once,
ReferenceStyle = SecurityTokenReferenceStyle.Internal
};
((AsymmetricSecurityBindingElement)sec).InitiatorTokenParameters = x509Params;
b.Elements.Add(sec);
b.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));
b.Elements.Add(new HttpsTransportBindingElement() { });
Please help me out if you have got any idea.
On the client side, by implementing the IClientMessageInspector interface to intercept SOAP messages.
public class ClientMessageLogger : IClientMessageInspector
{
public object AfterReceiveRequest(ref Message reply, object correlationState)
{
MessageHeader header = MessageHeader.CreateHeader("UserAgent", "http://User", "User1");
reply.Headers.Add(header);
return null;
}
public void BeforeSendRequest(ref Message request, IClientChannel channel)
{
MessageHeader header1 = MessageHeader.CreateHeader("Testreply", "http://Test", "Test");
request.Headers.Add(header1);
}
}
[AttributeUsage(AttributeTargets.Interface)]
public class CustomBehavior : Attribute, IContractBehavior
{
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
return;
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
return;
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
dispatchRuntime.MessageInspectors.Add(new CustomMessageInspector());
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
return;
}
}
Then, apply the CustContractBehavior feature to the service interface.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
[CustomBehavior]
public interface IDemo
When the client sends a request to the server, it will call BeforeSendRequest, and when the client receives the server reply message, it will call AfterReceiveReply.
What I'm trying to achieve is passing credentials/token to WCF services in every requests. BTW, this credential IS NOT windows credentials, they are fetched from custom db, and the authentication logic is quite simple, tenantId+username+password.
I'm currently using message inspector to insert these kind of information in the headers and fetch them from server-side inspector(using OperationContext).
But in order to stay thread-safe,I have to wrap the requests in every winform request like this:
using (new OperationContextScope((WcfService as ServiceClient).InnerChannel))
{
MessageHeader hdXXId = MessageHeader.CreateHeader("XXId", "CustomHeader", WinformSomeVariable.XXId);
OperationContext.Current.OutgoingMessageHeaders.Add(hdXXId);
_objXX = WcfService.GetXXById(id);
}
Like showed above, this is quite heavy and obviously not a smart way to handle this situation. So is there any way to hold these kind of information safely and can as well fetch them in the WCF Inspectors?
Many thanks!
PS. Thanks to #Abraham Qian, I was being silly the whole time. Just put the client inspector within the same winform project will solve this issue.
Just ignore the question of how to refactor your authentication for a moment.
As for how to use the IClientMessageInspector interface to create a persistent message header, the following code snippet might be useful (Assume that invocation by using Channel Factory)
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://localhost:1300");
IService service = ChannelFactory<IService>.CreateChannel(new BasicHttpBinding(), new EndpointAddress(uri));
try
{
Console.WriteLine(service.SayHello());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
[ServiceContract(Namespace = "mydomain")]
[CustomContractBehavior]
public interface IService
{
[OperationContract]
string SayHello();
}
public class ClientMessageLogger : IClientMessageInspector
{
public void AfterReceiveReply(ref Message reply, object correlationState)
{
string displayText = $"the client has received the reply:\n{reply}\n";
Console.Write(displayText);
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
//Add custom message header
request.Headers.Add(MessageHeader.CreateHeader("myheader","mynamespace",2000));
string displayText = $"the client send request message:\n{request}\n";
Console.WriteLine(displayText);
return null;
}
}
public class CustomContractBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute
{
public Type TargetContract => typeof(IService);
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
return;
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new ClientMessageLogger());
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
return;
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
return;
}
}
I have a wcf service where my interface looks something like this:
[ServiceContract]
public interface IMyService
{
[OperationContract]
[AllowedFileExtension]
void SaveFile(string fileName);
}
My goal is to inspect the incoming message to verify the fileName. So my AllowedFileExtensionAttribute class looks like this:
public class AllowedFileExtensionsAttribute : Attribute, IOperationBehavior
{
private readonly string _callingMethodName;
private readonly string[] _allowedFileExtension;
public AllowedFileExtensionsAttribute([CallerMemberName]string callingMethodName = null)
{
_callingMethodName = callingMethodName;
}
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
}
public void Validate(OperationDescription operationDescription)
{
}
}
Invoking this from for instance WCF Test Client or a simple console application, my Attribute class is not invoked, it goes directly to the implmentation. What am I doing wrong here?
You can use WCF MessageInspector to intercept the request and do whatever you wish to do.
A message inspector is an extensibility object that can be used in the service model's client runtime and dispatch runtime programmatically or through configuration and that can inspect and alter messages after they are received or before they are sent.
You can implement both IDispatchMessageInspector and IClientMessageInspector interfaces. Read the incoming data in the AfterReceiveRequest, store it in a threadstatic variable, and if required use it in BeforeSendRequest.
AfterReceiveRequest is invoked by the dispatcher when a message has been received in pipeline.You can manipulate this request which has been passed as reference parameter.
See the msdn doc.
public class SimpleEndpointBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(
new SimpleMessageInspector()
);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
public class SimpleMessageInspector : IClientMessageInspector, IDispatchMessageInspector
{
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
//modify the request send from client(only customize message body)
request = TransformMessage2(request);
//you can modify the entire message via following function
//request = TransformMessage(request);
return null;
}
}
Check this post for details.
I'm using asp.net core on windows and have a file with classes generated by the dotnet-svcutil. I'm using nlog for the logging purpose. Is there a way I can log all the raw requests and responses to and from the external service?
Already tried logman https://github.com/dotnet/wcf/blob/master/Documentation/HowToUseETW.md, but first - it doesn't show the raw soap, only events, and second - I need logs to be logged by the configured nlog.
Behaviour:
public class LoggingEndpointBehaviour : IEndpointBehavior
{
public LoggingMessageInspector MessageInspector { get; }
public LoggingEndpointBehaviour(LoggingMessageInspector messageInspector)
{
MessageInspector = messageInspector ?? throw new ArgumentNullException(nameof(messageInspector));
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(MessageInspector);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
Inspector:
public class LoggingMessageInspector : IClientMessageInspector
{
public LoggingMessageInspector(ILogger<LoggingMessageInspector> logger)
{
Logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
}
public ILogger<LoggingMessageInspector> Logger { get; }
public void AfterReceiveReply(ref Message reply, object correlationState)
{
using (var buffer = reply.CreateBufferedCopy(int.MaxValue))
{
var document = GetDocument(buffer.CreateMessage());
Logger.LogTrace(document.OuterXml);
reply = buffer.CreateMessage();
}
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
using (var buffer = request.CreateBufferedCopy(int.MaxValue))
{
var document = GetDocument(buffer.CreateMessage());
Logger.LogTrace(document.OuterXml);
request = buffer.CreateMessage();
return null;
}
}
private XmlDocument GetDocument(Message request)
{
XmlDocument document = new XmlDocument();
using (MemoryStream memoryStream = new MemoryStream())
{
// write request to memory stream
XmlWriter writer = XmlWriter.Create(memoryStream);
request.WriteMessage(writer);
writer.Flush();
memoryStream.Position = 0;
// load memory stream into a document
document.Load(memoryStream);
}
return document;
}
}
Usage:
if (configuration.GetValue<bool>("Logging:MessageContent"))
client.Endpoint.EndpointBehaviors.Add(serviceProvider.GetRequiredService<LoggingEndpointBehaviour>());
Found the answer here:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/extending/how-to-inspect-or-modify-messages-on-the-client
The order of actions:
Implement the System.ServiceModel.Dispatcher.IClientMessageInspector interface. Here you can inspect/modify/log messages
Implement a System.ServiceModel.Description.IEndpointBehavior or System.ServiceModel.Description.IContractBehavior depending upon the scope at which you want to insert the client message inspector.
System.ServiceModel.Description.IEndpointBehavior allows you to change behavior at the endpoint level.
System.ServiceModel.Description.IContractBehavior allows you to change behavior at the contract level.
Insert the behavior prior to calling the ClientBase.Open or the ICommunicationObject.Open method on the System.ServiceModel.ChannelFactory.
we are working with UPS shipment API and there are certain issues we are facing. After contacting UPS technical support, they have asked to provide them with the SOAP envelope (Request/Respose) in xml format.
Kindly assist that how can that be acquired from the code . below is the service call to UPS API.
ShipmentResponse shipmentReponse =
shipService.ProcessShipment(shipmentRequest);
any help appreciated.
If you want to do this from the program itself, you can add an endpoint behaviour, assuming you're using WCF, to save the soap request and response.
Usage would be something like this,
using (ChannelFactory<IService> scf = new ChannelFactory<IService>(new BasicHttpBinding(), "http://localhost:8000/Soap"))
{
scf.Endpoint.EndpointBehaviors.Add(new SimpleEndpointBehavior()); // key bit
IService channel = scf.CreateChannel();
string s;
s = channel.EchoWithGet("Hello, world");
Console.WriteLine(" Output: {0}", s);
}
It is described here in detail here: http://msdn.microsoft.com/en-us/library/ms733786%28v=vs.110%29.aspx, the key methods for you are AfterReceiveReply and BeforeSendRequest, where you can store or save the SOAP xml as necessary.
// Client message inspector
public class SimpleMessageInspector : IClientMessageInspector
{
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
// log response xml
File.WriteAllText(#"c:\temp\responseXml.xml", reply.ToString());
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
{
// log request xml
File.WriteAllText(#"c:\temp\requestXml.xml", request.ToString());
return null;
}
}
public class SimpleEndpointBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
// No implementation necessary
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new SimpleMessageInspector());
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
// No implementation necessary
}
public void Validate(ServiceEndpoint endpoint)
{
// No implementation necessary
}
}