2013-08-02 58 views
1

我有一個WCF web服務,它的工作很酷,有一些不同的客戶。如何以編程方式更改WCF服務BodyStyle?

某些客戶端使用它作爲XML和其他作爲JSON。 爲了有這種行爲,我設計了所有的服務,就好像他們有一個擴展。如果擴展名等於json,則返回JSON,否則返回XML。

下面的代碼顯示了我如何完成此行爲。

[WebGet(UriTemplate = "test.{PsFormat}")] 
    public string test(string PsFormat) { 
     DefineResponseFormat(PsFormat); 
     return "test"; 
    } 

    public static void DefineResponseFormat(string PsFormat) 
    { 
     OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; 
     if (PsFormat.ToLower() == "json") { 
      context.Format = WebMessageFormat.Json; 
      context.ContentType = "application/json; charset=utf-8"; 
     } 
     else if (PsFormat.ToLower() == "wjson") { 
      context.Format = WebMessageFormat.Json; 
      context.ContentType = "application/json; charset=utf-8"; 
      // CHANGE BodyStyle TO WRAPPED 
     } 
     else { 
      context.Format = WebMessageFormat.Xml; 
      context.ContentType = "text/xml; charset=utf-8"; 
     } 
    } 

的問題,是我一直所返回的JSON彷彿WebGet屬性BodyStyle = WebMessageBodyStyle.Bare,這是默認值。現在,我有一個新的客戶端需要對它進行調用,就像BodyStyle = WebMessageBodyStyle.Wrapped一樣。 (用上面代碼中的代碼表示,如果使用擴展名wjson。)

問題是:如何以編程方式更改BodyStyle值?

回答

相關問題