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
}
}
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.
I have a standalone C# WCF service running as a Windows service. I have the requirement to add custom headers like X-Frame-Options to all responses. I have tried to add an instance of the following class to ServiceEndpoint.Behaviors
internal class ServerInterceptor : IDispatchMessageInspector, IEndpointBehavior
{
object IDispatchMessageInspector.AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
void IDispatchMessageInspector.BeforeSendReply(ref Message reply, object correlationState)
{
reply.Properties.Add("X-Frame-Options", "deny");
}
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
void IEndpointBehavior.Validate(ServiceEndpoint endpoint) { }
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { }
}
This doesn't add any HTTP header to the response although the class gets called as the debugger can step into the BeforeSendReply function. Furthermore if I replace reply.Properties with reply.Headers then the header is added, but not to the HTTP headers but to the SOAP headers.
How can I add a HTTP header like X-Frame-Options to the response?
I made an example, which is used to add extra CORS HTTP header, wish it is instrumental for you.
Message Inspector.
public class CustomHeaderMessageInspector : IDispatchMessageInspector
{
Dictionary<string, string> requiredHeaders;
public CustomHeaderMessageInspector(Dictionary<string, string> headers)
{
requiredHeaders = headers ?? new Dictionary<string, string>();
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
string displayText = $"Server has received the following message:\n{request}\n";
Console.WriteLine(displayText);
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
if (!reply.Properties.ContainsKey("httpResponse"))
reply.Properties.Add("httpResponse", new HttpResponseMessageProperty());
var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
foreach (var item in requiredHeaders)
{
httpHeader.Headers.Add(item.Key, item.Value);
}
string displayText = $"Server has replied the following message:\n{reply}\n";
Console.WriteLine(displayText);
}
}
Custom Contract Attribute.
public class MyBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute
{
public Type TargetContract => typeof(MyBehaviorAttribute);
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
var requiredHeaders = new Dictionary<string, string>();
requiredHeaders.Add("Access-Control-Allow-Origin", "*");
requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
dispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
}
}
Apply the contract behavior.
[ServiceContract(Namespace = "mydomain")]
[MyBehavior]
public interface IService
{
[OperationContract]
[WebGet]
string SayHello();
}
Result.
Feel free to let me know if there is anything I can help with.
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 need to create a (WCF) client that communicates with a service that expects the messages to be signed. Since I'm quite new to WCF I first tried to setup a simple selfhost service and a client that talks to this servive.
Both the service and client have message inspectors so I can see what's going over the line.
The strange thing however is that the MessageInspector on the client is NOT showing any signing of the message, while the MessageInspector on the service is showing a Security header.
My question is, can I influence the moment the messageinspector get called, I guess that it is called before WCF signed the message.
I use the folowing code on then client side, with no additional config settings:
EndpointAddress address = new EndpointAddress("http://localhost:8001/Someplace/CalculatorService");
WSHttpBinding wsbinding = new WSHttpBinding(SecurityMode.Message);
ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(wsbinding, address);
factory.Endpoint.Behaviors.Add(new MyBehaviour());
factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser,
StoreName.My,X509FindType.FindBySubjectName, "MyCertificate");
factory.Credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.CurrentUser,
StoreName.AddressBook, X509FindType.FindBySubjectName, "MyCertificate");
ICalculator client = factory.CreateChannel();
var total = client.Add(10, 20);
....
class MyInspector : IClientMessageInspector
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
Console.WriteLine("IClientMessageInspector.AfterReceiveReply called.");
Console.WriteLine("Message: {0}", reply.ToString());
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
{
Console.WriteLine("IClientMessageInspector.BeforeSendRequest called.");
Console.WriteLine("Message: {0}", request.ToString());
return null;
}
class MyBehaviour : IEndpointBehavior
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
return;
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new MyInspector());
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
return;
}
}
No you can't control when in the pipeline the message inspectors are called. Instead of using message inspectors to inspect the messages, use WCF message tracing + svctraceviewer.exe instead.
http://msdn.microsoft.com/en-us/library/ms733025.aspx
http://msdn.microsoft.com/en-us/library/ms732023.aspx