在WCF服务中使用不同的POST数据

时间:2014-02-10 17:20:41

标签: c# .net web-services wcf rest

我在WCF Web服务中有两个接口,如下所示;

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
    UriTemplate = "GetTypes",
    BodyStyle = WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Json,
    RequestFormat = WebMessageFormat.Json)]
    string GetTypes();

    [OperationContract]
    [WebInvoke(Method = "POST",
    UriTemplate = "GetTypes",
    BodyStyle = WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Xml,
    RequestFormat = WebMessageFormat.Xml)]
    XmlDocument GetTypes();
}

基本上我想允许传入的请求支持Xml或Json形成。但我得到

的编译错误
  

类型'Service.Service'已经定义了一个名为'GetTypes'的成员   相同的参数类型为C:\ Projects \ WCF \ Service.svc.cs

为了克服这个错误,我可以编写如下代码;

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
    UriTemplate = "GetTypes",
    BodyStyle = WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Json,
    RequestFormat = WebMessageFormat.Json)]
    string GetTypes(string sJson);

    [OperationContract]
    [WebInvoke(Method = "POST",
    UriTemplate = "GetTypes",
    BodyStyle = WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Xml,
    RequestFormat = WebMessageFormat.Xml)]
    XmlDocument GetTypes(XmlDocument oXml);
}

GetTypes方法类似于;

public string GetTypes(string sJson)
{
    var sr = new StreamReader(sJson);
    string text = sr.ReadToEnd();
    //do something .... and return some Json
}

public XmlDocument GetTypes(XmlDocument oXml)
{
    var sr = new StreamReader(oXml);
    string text = sr.ReadToEnd();
    //do something .... and return a XmlDocument
}

这是实现这一目标的最佳方式,还是更好的选择。或者我最好有两种方法,如

  

GetTypesXml(XmlDocument oXml)

  

GetTypesJson(string sJson)

1 个答案:

答案 0 :(得分:1)

以下MSDN文章似乎解决了您所遇到的方法重载问题。

更改方法的返回类型不会使公共语言运行时规范中所述的方法具有唯一性。您无法定义仅因返回类型而异的重载。

http://msdn.microsoft.com/en-us/library/vstudio/ms229029(v=vs.100).aspx

如果您需要两个仅在返回类型上有所不同的类似方法,您可能需要考虑不同的方法名称,而不是尝试强制重载。 (例如GetTypesGetTypesXML