使用PostAsync将XML传输到自托管WCF服务
假设我使用BasicHttpsBinding提供了以下WCF服务:使用PostAsync将XML传输到自托管WCF服务,xml,wcf,https,Xml,Wcf,Https,假设我使用BasicHttpsBinding提供了以下WCF服务: [ServiceContract] public interface IHelloWorld { [OperationContract] void HelloWorld(); } 我必须如何更改它才能处理以下包含XML数据的PostAsync请求 httpContent = new StringContent(xmlDoc.ToString(), Encoding.UTF
[ServiceContract]
public interface IHelloWorld
{
[OperationContract]
void HelloWorld();
}
我必须如何更改它才能处理以下包含XML数据的PostAsync请求
httpContent = new StringContent(xmlDoc.ToString(), Encoding.UTF8, "application/xml");
httpClient.PostAsync(requestURI, httpContent);
还是有更好的方法
谢谢大家!
约翰,这是我的解决办法。我必须面对几个问题:选择哪个绑定(WebHttpBinding)、处理PostAsync(同步方法中的异步)以及防止StringWriter将UTF8更改为UTF16 在服务器端,界面如下所示:
[ServiceContract]
[XmlSerializerFormat]
public interface IHelloWorld
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "")]
void HelloWorld(MyRequest request);
}
var _serializer = new XmlSerializer(typeof(MyRequest));
StringContent _httpContent;
// We need to keep UTF8 encoding here (StringWriter uses UTF16 by default)
using (StringWriter _textWriter = new Utf8StringWriter())
{
_serializer.Serialize(_textWriter, _ebicsRequest);
_httpContent = new StringContent(_textWriter.ToString(), Encoding.UTF8, "application/xml");
}
HttpClient _httpClient = new HttpClient();
var task = _httpClient.PostAsync(_requestURI, _httpContent).Result;
属性XmlSerializerFormat指示WCF应该使用XMLSerializer而不是默认的DataContractSerializer。为了使其正常工作,必须使用[XmlElement]、[XmlAttribute]等对类MyRequest进行正确注释,请参阅
这是我配置WCF主机的地方:
WebServiceHost host = new WebServiceHost(typeof(HelloWorldService));
WebHttpBinding binding = new WebHttpBinding();
binding.Security.Mode = WebHttpSecurityMode.Transport;
var endpoint = host.AddServiceEndpoint(typeof(IHelloWorld), binding, _address);
endpoint.Behaviors.Add(new WebHttpBehavior());
host.Open();
在客户端,代码如下所示:
[ServiceContract]
[XmlSerializerFormat]
public interface IHelloWorld
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "")]
void HelloWorld(MyRequest request);
}
var _serializer = new XmlSerializer(typeof(MyRequest));
StringContent _httpContent;
// We need to keep UTF8 encoding here (StringWriter uses UTF16 by default)
using (StringWriter _textWriter = new Utf8StringWriter())
{
_serializer.Serialize(_textWriter, _ebicsRequest);
_httpContent = new StringContent(_textWriter.ToString(), Encoding.UTF8, "application/xml");
}
HttpClient _httpClient = new HttpClient();
var task = _httpClient.PostAsync(_requestURI, _httpContent).Result;
我在这里找到了Utf8StringWriter类:。我需要使用SOAP而不是XML吗?我试图在中重现答案,但到目前为止运气不佳。此外,我已根据此链接使用HTTPS配置了WCF服务