2013-03-06 64 views
0

是否可以使用.NET 4.0框架基於查詢字符串值更改WCF Rest響應的格式?我想根據查詢字符串值發送XML和JSON響應。基於查詢字符串的WCF ResponseFormat

[OperationContract] 
[WebGet(UriTemplate = "/list")] 
List<SomeObject> List(); 

[DataContract] 
public class SomeObject 
{ 
    private int id; 
    private string value; 

    private SomeObject() 
    { } 
    private SomeObject(int id, string value) 
    { 
     this.id = id; 
     this.value= value; 
    } 

    [DataMember(Order = 0)] 
    public int Id 
    { 
     get { return id; } 
     set { } 
    } 
    [DataMember(Order = 1)] 
    public string Value 
    { 
     get { return value; } 
     set { } 
    } 

    public static List<SomeObject> List() 
    { 
     // return a list of SomeObject 
    } 
} 

例如: www.mysite.com/list?format=xml會返回一個XML格式的響應和 www.mysite.com/list?format=json會返回一個JSON格式的響應

謝謝。

回答

1

您可以使用WebOperationContext.Current.OutgoingResponse對象的Format屬性來完成您想要的操作。在下面的代碼中看到一個例子。

public class StackOverflow_15237791 
{ 
    [DataContract] 
    public class SomeObject 
    { 
     private int id; 
     private string value; 

     private SomeObject() 
     { } 
     public SomeObject(int id, string value) 
     { 
      this.id = id; 
      this.value = value; 
     } 

     [DataMember(Order = 0)] 
     public int Id 
     { 
      get { return id; } 
      set { } 
     } 
     [DataMember(Order = 1)] 
     public string Value 
     { 
      get { return value; } 
      set { } 
     } 
    } 
    [ServiceContract] 
    public class Service 
    { 
     [WebGet(UriTemplate = "/list?format={format}")] 
     public List<SomeObject> List(string format) 
     { 
      if ("xml".Equals(format, StringComparison.OrdinalIgnoreCase)) 
      { 
       WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml; 
      } 
      else if ("json".Equals(format, StringComparison.OrdinalIgnoreCase)) 
      { 
       WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json; 
      } 
      else 
      { 
       throw new WebFaultException<string>("Format query string parameter required", HttpStatusCode.BadRequest); 
      } 
      return new List<SomeObject> 
      { 
       new SomeObject(1, "hello"), 
       new SomeObject(2, "world") 
      }; 
     } 
    } 
    public static void Test() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     WebClient c = new WebClient(); 
     Console.WriteLine(c.DownloadString(baseAddress + "/list?format=xml")); 
     c = new WebClient(); 
     Console.WriteLine(c.DownloadString(baseAddress + "/list?format=json")); 

     Console.Write("Press ENTER to close the host"); 
     Console.ReadLine(); 
     host.Close(); 
    } 
} 
+0

工作正常。謝謝Carlos。 – kyletme 2013-03-06 02:35:00

相關問題