没有 Display 方法的参数,它可以在浏览器中工作,即 http://localhost:2617/UserService.svc/test
当我添加一个参数时,我也无法浏览它。
我有以下契约(Contract)。
[ServiceContract]
public interface IUserService
{
[OperationContract]
[WebInvoke(Method="PUT",UriTemplate = "/tes/{name}",
BodyStyle=WebMessageBodyStyle.WrappedRequest)]
string Display(string name);
}
public string Display(string name)
{
return "Hello, your test data is ready"+name;
}
我正在尝试使用以下代码进行调用
string url = "http://localhost:2617/UserService.svc/test"; //newuser
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string xmlDoc1 = "<Display xmlns=\"\"><name>shiva</name></Display>";
req.Method = "POST";
req.ContentType = "application/xml";
byte[] bytes = Encoding.UTF8.GetBytes(xmlDoc1);
req.GetRequestStream().Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream responseStream = response.GetResponseStream();
var streamReader = new StreamReader(responseStream);
var soapResonseXmlDocument = new XmlDocument();
soapResonseXmlDocument.LoadXml(streamReader.ReadToEnd());
我无法获得该输出。请帮助我。
最佳答案
您的代码中有一些不太正确的地方。
客户端
在客户端上,您需要将命名空间指定为 tempuri,因为您尚未声明显式命名空间,因此您的客户端代码需要如下所示:
string url = "http://localhost:2617/UserService.svc/test"; //newuser
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string xmlDoc1 = "<Display xmlns=\"http://tempuri.org/\"><name>shiva</name></Display>";
req.Method = "POST";
req.ContentType = "application/xml";
byte[] bytes = Encoding.UTF8.GetBytes(xmlDoc1);
req.GetRequestStream().Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream responseStream = response.GetResponseStream();
var streamReader = new StreamReader(responseStream);
var soapResonseXmlDocument = new XmlDocument();
soapResonseXmlDocument.LoadXml(streamReader.ReadToEnd());
服务
在服务上UriTemplate
不太正确 - 您指定 /tes/{name}
这样就需要像 http://localhost:2617/UserService.svc/tes/shiva
这样的 URL但您想要将 XML 数据发布到正文中,因此您应该将其更改为 UriTemplate = "/test"
(我假设您的意思是测试,而不是问题中的 tes)。
此外,如果您想向其 POST 数据,该方法应该是 POST(客户端需要与服务匹配,我假设客户端上拥有的就是您想要的)。
因此,总而言之,您的 IUserService 应该如下所示:
[ServiceContract]
public interface IUserService
{
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/test",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string Display(string name);
}
关于Wcf客户端: Passing XML string in the WCF REST service using WebInvoke,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10005771/