C# 从Http客户端post方法(SOAP请求/响应)读取时Asp.net Web API挂起
Web API方法因响应较大而陷入死锁。有人能指出它在哪里陷入僵局吗。在for循环中调用相同的代码。 这是密码C# 从Http客户端post方法(SOAP请求/响应)读取时Asp.net Web API挂起,c#,xml,soap,async-await,dotnet-httpclient,C#,Xml,Soap,Async Await,Dotnet Httpclient,Web API方法因响应较大而陷入死锁。有人能指出它在哪里陷入僵局吗。在for循环中调用相同的代码。 这是密码 public async Task<string> GetXMLResponse(string baseUrl, string fullFileName, int countryId, HttpClient client, FileOperations objFileOperation, string outputfilePath) { try
public async Task<string> GetXMLResponse(string baseUrl, string fullFileName, int countryId, HttpClient client, FileOperations objFileOperation, string outputfilePath)
{
try
{
var fileData = new StringBuilder(objFileOperation.ReadFile(fullFileName));
var content = new StringContent(TransformToSOAPXml(fileData, countryId), Encoding.UTF8,
"application/xml");
//fileData.Clear();
//fileData.Capacity = 0;
SerilogMethods.LogCustomException(log, "Before sending to Tax Engine", "GetXMLResponse");
using (HttpResponseMessage response = await client.PostAsync(baseUrl, content))
{
// content = null;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
SerilogMethods.LogCustomException(log, "Started Recieving response from Tax Engine", "GetXMLResponse");
var resultContent = await response.Content.ReadAsStreamAsync();
StreamReader readStream = new StreamReader(resultContent, Encoding.UTF8);
var postresult = await readStream.ReadToEndAsync();
XDocument doc = XDocument.Parse(postresult);
doc.Save(outputfilePath);
readStream.Dispose();
resultContent.Dispose();
//File.WriteAllText(outputfilePath, await response.Content.ReadAsStringAsync());
SerilogMethods.LogCustomException(log, "File write Completed", "GetXMLResponse");
return "Success";
}
SerilogMethods.LogCustomException(log, "Error occured in Tax Engine", "GetXMLResponse");
//Log the SOAP response when the SOAP fails with an error message
if (response.Content != null)
{
throw new Exception(await response.Content.ReadAsStringAsync());
}
return null;
}
}
catch (Exception ex)
{
SerilogMethods.LogError(log, ex, "GetXMLResponse");
return null;
}
}
有人能指出为什么第二个解决方案有效,而第一个解决方案无效。我甚至必须在保存xml响应之前解析它您只能使用response.Content.ReadAsStringAsync()读取一次响应。您正在读取流对象,第一次读取后,流位置位于流的末尾,您无法再次读取。
StreamReader
获取您传递给它的流的所有权,并在您处理读取器时处理它。在此之后,您不应该自己处理流。@sellotape因此,如果我不处理流,上述代码是否有效streamreader@jdweng有没有办法读取和解析响应?有很多方法可以解析xml。最佳方法取决于需要解析的数据量、xml的大小和xml的结构。如果没有看到xml,我就说不出来。通常使用SOAP时,您通常需要解析整个xml,大多数人使用XmlSerialization,因为SOAP通常有一个模式,您可以使用xsd工具创建XmlSerialization所需的c#类。
File.WriteAllText(outputfilePath, await response.Content.ReadAsStringAsync());