I have added a wsdl file in my project as a service reference. The application sends SOAP messages to a particular device which then sends the response in SOAP format.
Is there a way to look at the actual SOAP message that is wrapped in XML? Having to turn on wireshark to look at the SOAP messages gets tedious.
You can use the SVCTraceViewer to trace what are the messages that are being sent to and fro for each service call. You just have to set up the config and WCF builds the log files with the .svclog extension.
More details on this tool and its associated configuration is here. This does not require any 3rd party tool or network inspectors to be run etc... This is out of the box from Microsoft.
You are probably looking for SOAP extension,
look at this post:
Get SOAP Message before sending it to the WebService in .NET
Use Fiddler to inspect the messages. Ref: Using fiddler.
In case of WCF it has a less-known way to intercept original XML - custom MessageEncoder. It works on low level, so it captures real byte content including any malformed xml.
If you want use this approach you need to wrap a standard textMessageEncoding with custom message encoder as new binding element and apply that custom binding to endpoint in your config.
Also there is an example how I did it in my project -
wrapping textMessageEncoding, logging encoder, custom binding element and config.
I just wrapped the SOAP xml writer method and then inside the method made an event when the writing is flushed:
protected override XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize)
{
VerboseXmlWriter xmlWriter = new VerboseXmlWriter(base.GetWriterForMessage(message, bufferSize));
xmlWriter.Finished += XmlWriter_Finished;
}
The Class for the VerboseXmlWriter goes like that (just the idea):
public sealed class VerboseXmlWriter : XmlWriter
{
private readonly XmlWriter _wrappedXmlWriter;
private readonly XmlTextWriter _buffer;
private readonly System.IO.StringWriter _stringWriter;
public event EventHandler Finished;
private void OnFinished(StringPayloadEventArgs e)
{
EventHandler handler = Finished;
handler?.Invoke(this, e);
}
public VerboseXmlWriter(XmlWriter implementation)
{
_wrappedXmlWriter = implementation;
_stringWriter = new System.IO.StringWriter();
_buffer = new XmlTextWriter(_stringWriter);
_buffer.Formatting = Formatting.Indented;
}
~VerboseXmlWriter()
{
OnFinished(new StringPayloadEventArgs(_stringWriter.ToString()));
}
public override void Flush()
{
_wrappedXmlWriter.Flush();
_buffer.Flush();
_stringWriter.Flush();
}
public string Xml
{
get
{
return _stringWriter?.ToString();
}
}
public override WriteState WriteState => _wrappedXmlWriter.WriteState;
public override void Close()
{
_wrappedXmlWriter.Close();
_buffer.Close();
}
public override string LookupPrefix(string ns)
{
return _wrappedXmlWriter.LookupPrefix(ns);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
_wrappedXmlWriter.WriteBase64(buffer, index, count);
_buffer.WriteBase64(buffer, index, count);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
_wrappedXmlWriter.WriteSurrogateCharEntity(lowChar, highChar);
_buffer.WriteSurrogateCharEntity(lowChar, highChar);
}
and so on...
Implement the interface XmlWriter with the same structure as the example overrides. I also made an event-args class to transport the SOAP message out.
public class StringPayloadEventArgs : EventArgs
{
public string Payload { get; }
public StringPayloadEventArgs(string payload)
{
Payload = payload;
}
}
You can also use the same idea for the incomming SOAP messages.
Related
First of all, I want to share my scenario what i want to build -
Scenario:
I am building a client app using wpf. In some cases, I need to call a web service to get data from the server. In order to do this, I added a web reference using wsld url. And I created a ServiceManager class that will call service method. For security reason, I need to add some header info at soap xml request for example, UserToken, SAML Token and so on. I can this from my ServiceManager class. But I want to add another class which will be called before sending request to the server. In that class, I will do something like adding security header to soap xml request with request and then send it to the server.
I used SOAP Extension to fulfill my purpose and it works well. But the problem is, every-time I need to add annotation in Reference.cs (for each web service reference) file at top of the service method. I believe that there is some other easiest way to make this working better than SOAP Extension. Is there any way where I can only call the service and a delegate class will be called automatically and I don't need to add any annotation to the reference file? I will share my sample code here.
ServiceManage class:
public class ServiceManager
{
public UserDataService dataService; //web service added at Web Reference
public ServiceManager()
{
dataService = new UserDataService();
getUserServiceRequest rqst = new getUserServiceRequest();
getUserServiceResponse resp = dataService.getUser(rqst);
}
}
Reference.cs
[TraceExtensionAttribute(Name = "First")]
public getUserServiceResponse getUser([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] getUserServiceRequest request) {
object[] results = this.Invoke("getUser", new object[] {
request});
return ((getUserServiceResponse)(results[0]));
}
TraceExtensionAttribute.cs
[AttributeUsage(AttributeTargets.Method)]
public class TraceExtensionAttribute : SoapExtensionAttribute
{
private string mstrName = null;
public override Type ExtensionType
{
get { return typeof(TraceExtension); }
}
public override int Priority
{
get { return 1; }
set { }
}
public string Name
{
get { return mstrName; }
set { mstrName = value; }
}
}
TraceExtension.cs
public class TraceExtension : SoapExtension
{
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attr){//..do something}
public override void Initialize(object initializer){//..do something}
public override Stream ChainStream(Stream stream){//...do something}
public override void ProcessMessage(SoapMessage message) {//..do something}
}
Finally, I found the solution. Just through out Web Reference and add Service Reference instead. Then go to the following link. It works for me.
I am trying to make an echo web service that replies back with the request content, regardless of what that content is. Just an endpoint listening for anything and spitting it back.
So for example if it is called with "hi", the response content is "hi". If it is called with a multi-part message containing a form data, the data comes back. If it is a JSON message then JSON comes back. This is regardless of what the actual content is or what url parameters are provided. Basically I want it to send the same thing back regardless of the mime type, don't try to interpret it, just spit it back.
I'm starting with the following:
[ServiceContract]
private interface IEchoService
{
[OperationContract]
[WebInvoke]
object Echo(object s);
}
private class EchoService : IEchoService
{
public object Echo(object s)
{
return s;
}
}
WebServiceHost host = new WebServiceHost(typeof(EchoService), new Uri("http://localhost:8002/"));
WebHttpBinding binding = new WebHttpBinding();
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IEchoService), binding, "echo");
Any ideas how to make this work? This just returns back a HTTP status code of bad request when called.
It looks like the answer is to use the System.ServiceModel.Channels.Message class.
[ServiceContract]
private interface IEchoService
{
[OperationContract]
[WebInvoke]
Message Echo(Message s);
}
private class EchoService : IEchoService
{
public Message Echo(Message s)
{
return s;
}
}
Using C# I'd like to take control over the reading of the HTTP Requests from a POST. Primarily to read the stream of a multipart/form-data file upload to track the stream as it's received from the client.
Using the ProcessRequest or the Async BeginProcessRequest the body has already been parsed by ASP.net / IIS.
Is there a way to override the built-in reading via a HTTPHandler, or will I have to use another mechanism?
Many thanks
Andy
Update - Added code example as requested, albeit no different to a normal class that's implemented IHttpHandler
public class MyHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
// The body has already been received by the server
// at this point.
// I need a way to access the stream being passed
// from the Client directly, before the client starts
// to actually send the Body of the Request.
}
}
It appears that you can capture the stream via the context.BeginRequest event of a HttpModule.
For example :
public class Test : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(onBeginRequest);
}
public void onBeginRequest(object sender, EventArgs e)
{
HttpContext context = (sender as HttpApplication).Context;
if( context == nul ) { return; }
if (context.Request.RawUrl.Contains("test-handler.ext"))
{
Logger.SysLog("onBeginRequest");
TestRead(context);
}
}
// Read the stream
private static void TestRead(HttpContext context)
{
using (StreamReader reader = new StreamReader(context.Request.GetBufferlessInputStream()))
{
Logger.SysLog("Start Read");
reader.ReadToEnd();
Logger.SysLog("Read Completed");
}
}
}
Really I was trying to avoid HttpModules, as they are processed for every .net request, so really I'd stil like to know how to do it via a HTTPHandler.
You can definitely do that by implementing an IHttpHandler.
This example will get you started. There is no need to override the built-in reading.
You receive all the data in the Request, and can process it as required.
I am implementing WCF service that exposes a method whose [OperationContract] is [XmlSerializerFormat]. I sometimes get request whose body is not valid XML. In such cases I want to log the original body, so I can know why it didn't constitute valid XML. However, I can't get it from the Message object, see my attempts (by implementing IDispatchMessageInspector interface):
public object IDispatchMessageInspector.AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
request.ToString(); // "... Error reading body: System.Xml.XmlException: The data at the root level is invalid. Line 1, position 1. ..."
request.WriteBody(...); // Serialization Exception, also in WriteMessage and other Write* methods
request.GetReaderAtBodyContents(...); // Same
HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; // no body in httpRequest
}
When looking in watch, request.messageData appears to contain the body - but that's a private member.
How can I get the message buffer without trying to deserialize it?
Yes, you need custom MessageEncoder, unlike message inspectors (IDispatchMessageInspector / IClientMessageInspector) it sees original byte content including any malformed XML data.
However it's not trivial how to implement this approach. You have to wrap a standard textMessageEncoding as custom binding element and adjust config file to use that custom binding.
Also you can see as example how I did it in my project - wrapping textMessageEncoding, logging encoder, custom binding element and config.
For the opposite direction (I am writing a WCF client and the server returns invalid XML), I was able to extract the raw reply message in IClientMessageInspector.AfterReceiveReply by
accessing the internal MessageData property of reply via Reflection, and then
accessing its Buffer property, which is an ArraySegment<byte>.
Something similar might be available for the request message on the server side; so it might be worth examining the request variable in the debugger.
I'm aware that this is not exactly what you are asking for (since you are on the server side, not on the client side), and I'm also aware that using reflection is error-prone and ugly. But since the correct solution is prohibitively complex (see baur's answer for details) and this "raw dump" is usually only required for debugging, I'll share my code anyways, in case it is helpful to someone in the future. It works for me on .NET Framework 4.8.
public void AfterReceiveReply(ref Message reply, object correlationState)
{
object messageData = reply.GetType()
.GetProperty("MessageData",
BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(reply, null);
var buffer = (ArraySegment<byte>)messageData.GetType()
.GetProperty("Buffer")
.GetValue(messageData, null);
byte[] rawData =
buffer.Array.Skip(buffer.Offset).Take(buffer.Count).ToArray();
// ... do something with rawData
}
And here's the full code of the EndpointBehavior:
public class WcfLogger : IEndpointBehavior
{
public byte[] RawLastResponseBytes { get; private set; }
// We don't need these IEndpointBehavior methods
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { }
public void Validate(ServiceEndpoint endpoint) { }
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new MessageCaptureInspector(this));
}
internal class MessageCaptureInspector : IClientMessageInspector
{
private WcfLogger logger;
public MessageCaptureInspector(WcfLogger logger)
{
this.logger = logger;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
// Ugly reflection magic. We need this for the case where
// the reply is not valid XML, and, thus, reply.ToString()
// only contains an error message.
object messageData = reply.GetType()
.GetProperty("MessageData",
BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(reply, null);
var buffer = (ArraySegment<byte>)messageData.GetType()
.GetProperty("Buffer")
.GetValue(messageData, null);
logger.RawLastResponseBytes =
buffer.Array.Skip(buffer.Offset).Take(buffer.Count).ToArray();
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
return null;
}
}
}
Usage:
var logger = new WcfLogger();
myWcfClient.Endpoint.EndpointBehaviors.Add(logger);
try
{
// ... call WCF method that returns invalid XML
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
File.SaveAllBytes(#"C:\temp\raw_response.bin", logger.RawLastResponseBytes);
// Use the exception message and examine raw_response.bin with
// a hex editor to find the problem.
UPDATE
Some others that have run into this issue appear to have created a Customer Message Encoder.
A message encoding binding element serializes an outgoing Message and
passes it to the transport, or receives the serialized form of a
message from the transport and passes it to the protocol layer if
present, or to the application, if not present.
I am writing a media type formatter for HTML to automatically generate a Razor view based on an html request from the user. I am doing this for use inside a SelfHosted service. I need to detect what controller/action was requested to allow me to pick the view to render into.
public class RazorHtmlMediaTypeFormatter : MediaTypeFormatter
{
public RazorHtmlMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
public override bool CanWriteType(Type type)
{
return true;
}
public override bool CanReadType(Type type)
{
return false;
}
public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, System.Net.TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
var view = Razor.Resolve(String.Format("{0}.{1}.cshtml", something.Controller, something.Action), value);
byte[] buf = System.Text.Encoding.Default.GetBytes(view.Run(new ExecuteContext()));
stream.Write(buf, 0, buf.Length);
stream.Flush();
});
}
}
Why not wrapping your returned objects in Metadata<T>?
I.e. return, instead of MyCustomObject, Metadata<MyCustomObject>. As Metadata properties, you can set controller name and action. Then in the formatter, just decouple the Metadata and your custom object, and serialize just that custom object.
I blogged about this approach here - http://www.strathweb.com/2012/06/extending-your-asp-net-web-api-responses-with-useful-metadata/. While the purpose of the article is a bit different, I am sure you can relate it to your needs.
Edit: or if you are OK with a small hack, use a custom filter and headers:
public override void OnActionExecuting(HttpActionContext actionContext)
{
actionContext.Response.Headers.Add("controller", actionContext.ActionDescriptor.ControllerDescriptor.ControllerName);
actionContext.Response.Headers.Add("action", actionContext.ActionDescriptor.ActionName;);
base.OnActionExecuting(actionContext);
}
then just read it from the headers in the formatter, and remove the header entries so that they don't get sent to the client.
Web API Contrib has a working RazorViewFormatter in here.