2012-08-22 32 views
0

當我嘗試使用通用消息處理程序時,如果我使用我自己的類型(如text/x-json),accept或content-type爲html/xml/json時會遇到錯誤,所有消息都按預期工作分發給我的處理程序,流將數據返回給Web客戶端。我已經通過調試器完成了這一步,並且我的代碼成功創建了消息,但在服務總線綁定扼流圈中出現了一些信息,並導致服務器無法響應。是否需要更改設置以允許應用程序/ json,並使服務總線發送原始數據而不是嘗試重新進行串行化?如何將WebHttpRelayBinding與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()); 
} 
+0

你試過'[WebGet(UriTemplate = 「*」,ResponseFormat = WebMessageFormat.Json) ]'? – TheDude

+0

我沒有,bug不是每個路線返回json。 –

回答

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(); 
    } 
} 
相關問題