我有一個WCF服務,需要由第三方應用程序調用,發佈一些原始XML。嘗試使用WebRequest調用WCF服務
我想通過構建一個簡單的WebRequest並向服務發出請求來測試我的服務。
這裏是我的服務代碼:
接口:
[ServiceContract(Namespace = "http://test.mydomain.com")]
public interface ITest
{
[WebInvoke(UriTemplate = "", BodyStyle = WebMessageBodyStyle.Bare, Method="POST")]
[OperationContract]
Stream SaveXML(Stream input);
}
服務:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(Namespace = "http://test.mydomain.com")]
public class Test : ITest
{
public Stream SaveXML(Stream input)
{
StreamReader streamReader = new StreamReader(input);
string rawString = streamReader.ReadToEnd();
streamReader.Dispose();
// here need to save the input stream to xml format file
Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
byte[] returnBytes = encoding.GetBytes(rawString);
return new MemoryStream(returnBytes);
}
}
配置:
<services>
<service behaviorConfiguration="Blah.TestBehavior" name="Blah.Test">
<endpoint address="http://localhost:51494/Blah/Test.svc" binding="basicHttpBinding" contract="Blah.ITest">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
錯誤的客戶端代碼:
string postData = "<Message version=\"1.5\" xmlns=\"http://test.mydomain.com\" ><books>Blah</books></Message>";
WebRequest request = WebRequest.Create("http://localhost:51494/Blah/Test.svc/SaveXML");
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "text/xml; charset=utf-8";
//request.ContentType = "text/xml;";
//request.ContentType = "application/xml;";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
在最後一行我得到一個400(壞請求)或415(不支持的媒體類型)錯誤,這取決於我的contentType指定。另外,如果我在我的客戶端應用程序中添加服務引用,並使用API調用服務,那麼它可以正常工作。任何見解都將不勝感激,因爲我是WCF的新手,並且完全陷入困境。
我會做什麼:使用Fiddler http://fiddler2.com/fiddler2/來查看「API」的請求 - 一個工程。然後將它與不起作用的請求進行比較。這應該縮小它的範圍。 – Cheeso 2010-03-04 20:49:17
您的'StreamReader'需要位於'using'塊中,就像其他幾個對象一樣。即使拋出異常,'使用'塊也會導致它們被丟棄。 – 2010-03-04 21:23:41