如何在WCF的帮助下通过邮寄发送xml数据?
例如,我有一些代码:
public interface IServiceForILobby
{
[OperationContract]
[WebInvoke(Method = "POST")]
string SendXml(string response);
}
Run Code Online (Sandbox Code Playgroud)
//这是主持人
static void Main(string[] args)
{
Console.WriteLine("*Console Based Rest HOST*");
using (WebServiceHost serviceHost = new WebServiceHost(typeof(ServiceForILobby)))
{
serviceHost.Open();
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
/*这是客户*/
using (ChannelFactory<IServiceForILobby> cf = new ChannelFactory<IServiceForILobby>(new WebHttpBinding(), "http://192.168.1.103:50000/RestService/SendXml?response={x}"))
{
cf.Endpoint.EndpointBehaviors.Add(new WebHttpBehavior());
IServiceForILobby channel = cf.CreateChannel();
string s;
// s = channel.SendXml("http://192.168.1.103:50000/RestService/SendXml?response={x}");
string a;
using (StreamReader sr = new StreamReader("simplexml.txt"))
{
string xmlCode = sr.ReadToEnd();
s = channel.SendXml(xmlCode);
}
Run Code Online (Sandbox Code Playgroud)
我想将XML从客户端发送到主机,然后像这样解析它如何解析XML文件?
小智 10
为了通过POST发送xml数据,您需要根据WCF服务正确构建数据.这基本上是你需要的:
1)WCF服务接口
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "GetData",
RequestFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare)]
string GetData(DataRequest parameter);
Run Code Online (Sandbox Code Playgroud)
2)WCF服务实现
public string GetData(DataRequest parameter)
{
//Do stuff
return "your data here";
}
Run Code Online (Sandbox Code Playgroud)
3)WCF服务中的数据合同(在这种情况下,它是DataRequest)
[DataContract(Namespace = "YourNamespaceHere")]
public class DataRequest
{
[DataMember]
public string ID{ get; set; }
[DataMember]
public string Data{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
4)发送数据的客户必须正确构建数据!(在这种情况下是C#控制台应用程序)
static void Main(string[] args)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string SampleXml = "<DataRequest xmlns=\"YourNamespaceHere\">" +
"<ID>" +
yourIDVariable +
"</ID>" +
"<Data>" +
yourDataVariable +
"</Data>" +
"</DataRequest>";
string postData = SampleXml.ToString();
byte[] data = encoding.GetBytes(postData);
string url = "http://localhost:62810/MyService.svc/GetData";
string strResult = string.Empty;
// declare httpwebrequet wrt url defined above
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
// set method as post
webrequest.Method = "POST";
// set content type
webrequest.ContentType = "application/xml";
// set content length
webrequest.ContentLength = data.Length;
// get stream data out of webrequest object
Stream newStream = webrequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
//Gets the response
WebResponse response = webrequest.GetResponse();
//Writes the Response
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream);
string s = sr.ReadToEnd();
return s;
}
Run Code Online (Sandbox Code Playgroud)