我一直在尝试做的是加载任何XML文件并使用POST和HTTP将其作为参数传递。我遇到的问题是,我无法在客户端获得响应,甚至在本地浏览Service1.svc / XMLTest时也无法获得响应。我的代码如下: service.svc:
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;
using System.Xml;
namespace XMLService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class Service1 :IService1
{
public string XMLTest(Stream XMLParam)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml("D:\\test.xml");
return xDoc.OuterXml;
}
}
}
Iservice1.cs
namespace XMLService
{// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "Post", UriTemplate = "XMLTest")]
string XMLTest(Stream XMLParam)
}
}
Web Config
<system.serviceModel>
<services>
<!-- Note: the service name must match the configuration name for the service implementation. -->
<service name="XMLService.Service1" behaviorConfiguration="Default" >
<endpoint address ="" contract="XMLService.IService1"
binding="webHttpBinding" behaviorConfiguration="web" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Default">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
客户端Asp.Net页面,我使用“发布”和“HTTP”调用WCF
protected void Button1_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:23457/Service1.svc/XMLTest");
request.Method = "POST"; // Set the Method property of the request to POST.
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest and Length
request.ContentType = "application / x - www - form - urlencoded"; //"text/xml";
request.ContentLength = byteArray.Length;
//Load the XML Document
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml("D:\\test.xml");
string rawXml = xDoc.OuterXml;
// Get the request stream, write the data to the request stream
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//Web Response, display the status,
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}