【发布时间】: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