I have a WCF Operation that returns a List of Colors:
public List<Color> GetCol开发者_开发技巧ors()
{
List<Color> colors = new List<Color>();
colors.Add(new Color {Name = "Red", Code = 1});
colors.Add(new Color {Name = "Blue", Code = 2});
return colors;
}
When I run this in the WCF Test Client, it works fine and I can see the array of colors, but what I would actually like is if it returned the XML Response and then I could set a RichTextBox
's Text to the contents of the xml. How can I do this?
If you want the XML representation of the list return to the client my advice would be to serialize the list and return it as a string to the client.
Here is some code that can get you started. Haven't tested it but I think it might be easy for you to change.
public string GetColorsXmlRepresentation()
{
var colors = new List<Color>();
colors.Add(new Color {Name = "Red", Code = 1});
colors.Add(new Color {Name = "Blue", Code = 2});
return Serialize<List<Color>>(colors);
}
public string Serialize<T>(T instance)
{
var data = new StringBuilder();
var serializer = new DataContractSerializer(instance.GetType());
using (var writer = XmlWriter.Create(data))
{
serializer.WriteObject(writer, instance);
writer.Flush();
return data.ToString();
}
}
Hope it helps
If you want your WCF service to return XML, then make it return XML. If you want it to return List<Color>
, then it should return List<Color>
.
You can't use open generics in WCF contracts. SOAP doesn't have any support for generics.
精彩评论