你可以使用对象的Format
属性WebOperationContext.Current.OutgoingResponse
来完成你想要的。请参阅下面代码中的示例。
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();
}
}