gpt4 book ai didi

c# - 带有 SOAP 服务的 Dotnet 核心

转载 作者:行者123 更新时间:2023-11-30 20:30:19 26 4
gpt4 key购买 nike

我们有一个 ASP.NET Core 系统,我们需要使用 SOAP 连接到另一个 Web 服务(我们从客户那里收到了 WSDL)。

过去,我们应该在 Visual Studio 中使用 WCF 选项来使用“添加服务引用”。

对于 dotnet 核心项目,选项不再可用,但有几个选项可以获得相同的解决方案:

在命令行中使用 SvcUtil 或在此处安装插件 https://blogs.msdn.microsoft.com/webdev/2016/06/26/wcf-connected-service-for-net-core-1-0-0-and-asp-net-core-1-0-0-is-now-available/生成.cs文件

这两种解决方案都需要与这些 nuget 包结合使用 https://github.com/dotnet/wcf

所以我的问题是:除了使用 WCF 在 C# 中访问 SOAP 服务之外,还有其他解决方案吗?

最佳答案

您可以使用类似 Soap UI 的工具获取 xml 请求的实际格式。

然后您可以使用 WebRequest 执行请求 - 类似于下面的代码。据我所知,没有办法自动生成类,因此您必须自己进行反序列化:

    public async static Task<string> CallWebService(string webWebServiceUrl, 
string webServiceNamespace,
string methodVerb,
string methodName,
Dictionary<string, string> parameters) {
const string soapTemplate =
@"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:{0}=""{2}"">
<soapenv:Header />
<soapenv:Body>
<{0}:{1}>
{3}
</{0}:{1}>
</soapenv:Body>
</soapenv:Envelope>";

var req = (HttpWebRequest)WebRequest.Create(webWebServiceUrl);
req.ContentType = "text/xml"; //"application/soap+xml;";
req.Method = "POST";

string parametersText;

if (parameters != null && parameters.Count > 0)
{
var sb = new StringBuilder();
foreach (var oneParameter in parameters)
sb.AppendFormat(" <{0}>{1}</{0}>\r\n", oneParameter.Key, oneParameter.Value);

parametersText = sb.ToString();
}
else
{
parametersText = "";
}

string soapText = string.Format(soapTemplate,
methodVerb, methodName, webServiceNamespace, parametersText);

Console.WriteLine("SOAP call to: {0}", webWebServiceUrl);
Console.WriteLine(soapText);

using (Stream stm = await req.GetRequestStreamAsync())
{
using (var stmw = new StreamWriter(stm))
{
stmw.Write(soapText);
}
}

var responseHttpStatusCode = HttpStatusCode.Unused;
string responseText = null;

using (var response = (HttpWebResponse)req.GetResponseAsync().Result) {
responseHttpStatusCode = response.StatusCode;

if (responseHttpStatusCode == HttpStatusCode.OK)
{
int contentLength = (int)response.ContentLength;

if (contentLength > 0)
{
int readBytes = 0;
int bytesToRead = contentLength;
byte[] resultBytes = new byte[contentLength];

using (var responseStream = response.GetResponseStream())
{
while (bytesToRead > 0)
{
// Read may return anything from 0 to 10.
int actualBytesRead = responseStream.Read(resultBytes, readBytes, bytesToRead);

// The end of the file is reached.
if (actualBytesRead == 0)
break;

readBytes += actualBytesRead;
bytesToRead -= actualBytesRead;
}

responseText = Encoding.UTF8.GetString(resultBytes);
//responseText = Encoding.ASCII.GetString(resultBytes);
}
}
}
}
return responseText;
//return responseHttpStatusCode;
}

关于c# - 带有 SOAP 服务的 Dotnet 核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44966560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com