Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 发送和接收SOAP消息_C#_Web Services_Soap - Fatal编程技术网

C# 发送和接收SOAP消息

C# 发送和接收SOAP消息,c#,web-services,soap,C#,Web Services,Soap,我正在用C#编写一个web服务客户端,不想创建和序列化/反序列化对象,而是发送和接收原始XML 这在C#中可能吗?您可以让web服务方法返回包含xml的字符串,但请注意上面关于使事情更容易出错的注释。是-您可以简单地将输入和输出声明为XmlNode [WebMethod] public XmlNode MyMethod(XmlNode input); 您可以使用System.Net类(如HttpWebRequest和HttpWebResponse)直接读取和写入HTTP连接 这里有一个基本的(

我正在用C#编写一个web服务客户端,不想创建和序列化/反序列化对象,而是发送和接收原始XML


这在C#中可能吗?

您可以让web服务方法返回包含xml的字符串,但请注意上面关于使事情更容易出错的注释。

是-您可以简单地将输入和输出声明为
XmlNode

[WebMethod]
public XmlNode MyMethod(XmlNode input);

您可以使用System.Net类(如HttpWebRequest和HttpWebResponse)直接读取和写入HTTP连接

这里有一个基本的(即兴的,未编译的,非错误检查的,非常简单的)示例。可能不是100%正确,但至少会让您了解其工作原理:

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(url);
req.ContentLength = content.Length;
req.Method = "POST";
req.GetRequestStream().Write(Encoding.ASCII.GetBytes(content), 0, content.Length);
HttpWebResponse resp = (HttpWebResponse) req.getResponse();
//Read resp.GetResponseStream() and do something with it...

这种方法效果很好但是您需要做的任何事情都可以通过继承现有的代理类并重写需要具有不同行为的成员来完成。在我的经验中,这种类型的东西最适合在没有其他选择的情况下使用。

这是我刚刚基于John M Gant的示例运行的一个实现的一部分。设置内容类型请求标头非常重要。再加上我的要求需要的证件

protected virtual WebRequest CreateRequest(ISoapMessage soapMessage)
{
    var wr = WebRequest.Create(soapMessage.Uri);
    wr.ContentType = "text/xml;charset=utf-8";
    wr.ContentLength = soapMessage.ContentXml.Length;

    wr.Headers.Add("SOAPAction", soapMessage.SoapAction);
    wr.Credentials = soapMessage.Credentials;
    wr.Method = "POST";
    wr.GetRequestStream().Write(Encoding.UTF8.GetBytes(soapMessage.ContentXml), 0, soapMessage.ContentXml.Length);

    return wr;
}

public interface ISoapMessage
{
    string Uri { get; }
    string ContentXml { get; }
    string SoapAction { get; }
    ICredentials Credentials { get; }
}

你真的需要SOAP,还是只想来回发送XML?+1谢谢你的帖子。我也发布了我对你建议的实现。谢谢,但是如何使用它呢?WebRequest=CreateRequest(soapMessage);WebResponse WebResponse=request.GetResponse()@在实现ISoapMessage接口时,我需要创建一个新的SoapMessage类吗?@hellowahab只需将该接口放在任何类上,并将其传递进来。或者将接口作为CreateRequest的一个参数删除,并改用ISoapMessage中的四个参数中的每一个。