如何将WebHttpRelayBinding与application / json请求一起使用?

时间:2012-08-22 16:45:21

标签: azure servicebus webhttprelaybinding

当我尝试使用通用消息处理程序时,我在接受时遇到错误,或者内容类型是html / xml / json,如果我使用我自己的类型,例如text / x-json,一切都按预期工作被分派给我的处理程序,流将数据返回给webclient。我已经通过调试器逐步完成了这一步,我的代码成功地创建了消息,但是在servicebus绑定ch​​okes中的某些内容导致服务器无法响应。是否需要更改设置以允许application / json并使服务总线发送原始数据而不是尝试重新序列化?

[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 个答案:

答案 0 :(得分:0)

您可以在更改后使用以下内容而不是使用:StreamMessageHelper.CreateMessage:

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();
    }
}