我有一个 ServiceContract 描述 WCF 服务中使用的方法。该方法具有定义 UriTemplate 和 ResponseFormat 的 WebGet 属性。
我想重用单个方法并拥有多个具有不同 UriTemplate 和不同 ResponseFormat 的 WebGet 属性。基本上我希望避免使用多种方法来区分返回类型是 XML 与 JSON 等。不过,在到目前为止我看到的所有示例中,我都需要为每个 WebGet 属性创建不同的方法。这是一个示例操作合同
[ServiceContract]
public interface ICatalogService
{
[OperationContract]
[WebGet(UriTemplate = "product/{id}/details?format=xml", ResponseFormat = WebMessageFormat.Xml)]
Product GetProduct(string id);
[OperationContract]
[WebGet(UriTemplate = "product/{id}/details?format=json", ResponseFormat = WebMessageFormat.Json)]
Product GetJsonProduct(string id);
}
使用上面的示例,我想对 xml 和 json 返回类型使用 GetProduct 方法,如下所示:
[ServiceContract]
public interface ICatalogService
{
[OperationContract]
[WebGet(UriTemplate = "product/{id}/details?format=xml", ResponseFormat = WebMessageFormat.Xml)]
[WebGet(UriTemplate = "product/{id}/details?format=json", ResponseFormat = WebMessageFormat.Json)]
Product GetProduct(string id);
}
有没有办法实现这一点,这样我就不会为了返回不同的响应格式而编写不同的方法?
Thanks!
你可以这样做
[ServiceContract]
public interface ICatalogService
{
[OperationContract]
[WebGet(UriTemplate = "product/{id}/details?format={format}")]
Stream GetProduct(string id, string format);
}
然后在代码中根据参数指定的值处理序列化。
对于 XML,编写一个处理序列化的帮助器方法。
public static Stream GetServiceStream(string format, string callback, DataTable dt, SyndicationFeed sf)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
if (format == "xml")
{
XmlSerializer xmls = new XmlSerializer(typeof(DataTable));
xmls.Serialize(writer, dt);
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
}
else if (format == "json")
{
var toJSON = new JavaScriptSerializer();
toJSON.RegisterConverters(new JavaScriptConverter[] { new JavaScriptDataTableConverter() });
writer.Write(toJSON.Serialize(dt));
WebOperationContext.Current.OutgoingResponse.ContentType = "text/json";
}
else if (format == "jsonp")
{
var toJSON = new JavaScriptSerializer();
toJSON.RegisterConverters(new JavaScriptConverter[] { new JavaScriptDataTableConverter() });
writer.Write(callback + "( " + toJSON.Serialize(dt) + " );");
WebOperationContext.Current.OutgoingResponse.ContentType = "text/json";
}
else if (format == "rss")
{
XmlWriter xmlw = new XmlTextWriter(writer);
sf.SaveAsRss20(xmlw);
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
}
else if (format == "atom")
{
XmlWriter xmlw = new XmlTextWriter(writer);
sf.SaveAsAtom10(xmlw);
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
}
else
{
writer.Write("Invalid formatting specified.");
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
}
writer.Flush();
stream.Position = 0;
return stream;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)