サードパーティのアプリから呼び出す必要のあるWCFサービスがあり、生のXMLを投稿しています。
単純な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();
その最後の行で、指定したContentTypeに応じて、400(不正な要求)または415(サポートされていないメディアタイプ)エラーが発生します。
また、クライアントアプリにサービス参照を追加し、APIを使用してサービスを呼び出すと、正常に機能します。私はWCFを初めて使用し、完全に困惑しているので、洞察をいただければ幸いです。