【问题标题】:Consume different POST data in WCF service在 WCF 服务中使用不同的 POST 数据
【发布时间】:2026-01-16 09:25:01
【问题描述】:

我在 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(字符串 sJson)

【问题讨论】:

  • 这是基本的c#,两个同名的方法只是参数不同,而不是返回类型不同。

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


【解决方案1】:

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

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

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

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

【讨论】:

  • 是否有类似的方法,只是返回类型不同,这是我唯一的选择吗?
  • 我认为你要么需要两种方法,要么需要两个端点。以下链接描述了后者:*.com/questions/186631/…