How can I use WebHttpRelayBinding with application/json requests?

396 Views Asked by At

When I try to use a generic message handler, I run into errors when the accept, or content-type is html/xml/json if I use my own type such as text/x-json everything works as expected the message is dispatched to my handlers and the stream returns the data to the webclient. I have stepped through this with a debugger and my code successfully creates the message but something in the servicebus binding chokes and causes the server not to respond. Is there a setting I need to change to allow application/json and make the service bus send raw data rather then trying to reserialize it?

[WebGet( UriTemplate = "*" )]
[OperationContract( AsyncPattern = true )]
public IAsyncResult BeginGet( AsyncCallback callback, object state )
{
    var context = WebOperationContext.Current;
    return DispatchToHttpServer( context.IncomingRequest, null, context.OutgoingResponse, _config.BufferRequestContent, callback, state );
}

public Message EndGet( IAsyncResult ar )
{
    var t = ar as Task<Stream>;
    var stream = t.Result;
    return StreamMessageHelper.CreateMessage( MessageVersion.None, "GETRESPONSE", stream ?? new MemoryStream() );
}
1

There are 1 best solutions below

0
On

Instead of using: StreamMessageHelper.CreateMessage, you can use the following one after you change :

WebOperationContext.Current.OutgoingResponse.ContentTYpe = "application/json"


public Message CreateJsonMessage(MessageVersion version, string action, Stream jsonStream)
{
    var bodyWriter = new JsonStreamBodyWriter(jsonStream);
    var message = Message.CreateMessage(version, action, bodyWriter);
    message.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
    return message;
}

class JsonStreamBodyWriter : BodyWriter
{
    Stream jsonStream;
    public JsonStreamBodyWriter(Stream jsonStream)
        : base(false)
    {
        this.jsonStream = jsonStream;
    }

    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        writer.WriteNode(JsonReaderWriterFactory.CreateJsonReader(this.jsonStream, XmlDictionaryReaderQuotas.Max), false);
        writer.Flush();
    }
}