我需要一些帮助来找到问题,我真的迷失了这里。我已经是一名开发人员,但我现在使用 C# 大约三个月了。
先从环境开始吧:
本地:
临时服务器
我有两个解决方案:DLL (.NET Standard 2.0) 和我的 API (.NET 6.0)。
我想我有一个简单的问题......当我从 Visual Studio 运行可能的 API 或当我在本地 IIS 中发布和运行时,工作正常。但是,当我将发布文件复制到临时服务器时,不起作用。
在登台服务器中,还有其他团队的另一个项目运行良好,所有项目都在 .NET Framework 中,我的项目是唯一在 .NET Core 中的。
这是
InnerException.StackTrace
的输出:
System.Net.HttpWebRequest.GetResponse() 处的错误[[[发送请求时发生错误。]]] 在 Uni.Business.DFe.ConsumirBase.ExecutarServico(XmlDocument xml,对象 servico,X509Certificate2 证书) 在 Uni.Business.DFe.Servicos.ServicoBase.Executar() 在 Uni.Business.DFe.Servicos.NFCom.ServicoBase.Executar() 在 C 中的 NFeModelo62.Handlers.RecepcaoHandler.HandleStatusServico62() 处: epositorios\git\NFeModelo62\NFeModelo62Api\NFeModelo62Api\NFeModelo62\Handlers\RecepcaoHandler.cs:第 366 行 [[[发送请求时发生错误。]]] 在 System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage 请求,布尔异步) , CancellationToken 取消令牌) 在 System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage 请求,布尔异步,布尔 doRequestAuth,CancellationToken CancellationToken) 在System.Net.Http.HttpMessageHandlerStage.Send(HttpRequestMessage请求,CancellationToken取消令牌) 在 System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage 请求,布尔异步,CancellationToken CancellationToken) 在System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage请求,布尔异步,CancellationToken取消令牌) 在System.Net.Http.HttpMessageHandlerStage.Send(HttpRequestMessage请求,CancellationToken取消令牌) 在System.Net.Http.SocketsHttpHandler.Send(HttpRequestMessage请求,CancellationToken取消令牌) 在System.Net.Http.HttpMessageInvoker.Send(HttpRequestMessage请求,CancellationToken取消令牌) 在System.Net.Http.HttpClient.Send(HttpRequestMessage请求,HttpCompletionOption完成选项,CancellationToken取消令牌) 在 System.Net.HttpWebRequest.SendRequest(布尔异步) 在 System.Net.HttpWebRequest.GetResponse()
这是生成异常的方法
/// <summary>
/// Estabelece conexão com o Webservice e faz o envio do XML e recupera o retorno. Conteúdo retornado pelo webservice pode ser recuperado através das propriedades RetornoServicoXML ou RetornoServicoString.
/// </summary>
/// <param name="xml">XML a ser enviado para o webservice</param>
/// <param name="servico">Parâmetros para execução do serviço (parâmetros do soap)</param>
/// <param name="certificado">Certificado digital a ser utilizado na conexão com os serviços</param>
public void ExecutarServico(XmlDocument xml, object servico, X509Certificate2 certificado)
{
var soap = (WSSoap)servico;
if (certificado == null && soap.UsaCertificadoDigital)
{
throw new CertificadoDigitalException();
}
TratarScapeEnvio = false;
TratarScapeRetorno = false;
if (soap.SoapString.IndexOf("{xmlBodyScape}") > 0)
{
TratarScapeEnvio = true;
TratarScapeRetorno = true;
}
else if (soap.SoapString.IndexOf("{xmlBodyScapeEnvio}") > 0)
{
TratarScapeEnvio = true;
TratarScapeRetorno = false;
}
else if (soap.SoapString.IndexOf("{xmlBodyScapeRetorno}") > 0)
{
TratarScapeEnvio = false;
TratarScapeRetorno = true;
}
var urlpost = new Uri(soap.EnderecoWeb);
var soapXML = EnveloparXML(soap, xml.OuterXml);
var buffer2 = Encoding.UTF8.GetBytes(soapXML);
ServicePointManager.Expect100Continue = false;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RetornoValidacao);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(urlpost);
httpWebRequest.Headers.Add("SOAPAction: " + soap.ActionWeb);
httpWebRequest.CookieContainer = cookies;
httpWebRequest.Timeout = soap.TimeOutWebServiceConnect;
httpWebRequest.ContentType = (string.IsNullOrEmpty(soap.ContentType) ? "application/soap+xml; charset=utf-8;" : soap.ContentType);
httpWebRequest.Method = "POST";
if (soap.UsaCertificadoDigital)
{
httpWebRequest.ClientCertificates.Add(certificado);
}
httpWebRequest.ContentLength = buffer2.Length;
//Definir dados para conexão com proxy
if (soap.Proxy != null)
{
httpWebRequest.Proxy = soap.Proxy;
}
var postData = httpWebRequest.GetRequestStream();
postData.Write(buffer2, 0, buffer2.Length);
postData.Close();
WebException webException = null;
WebResponse responsePost = null;
try
{
responsePost = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception e)
{
throw;
}
//catch (WebException ex)
//{
// webException = ex;
// responsePost = ex.Response;
// if (ex.Response == null)
// {
// throw (ex);
// }
//}
var streamPost = responsePost.GetResponseStream();
var encoding = Encoding.GetEncoding(soap.EncodingRetorno);
var streamReaderResponse = new StreamReader(streamPost, encoding);
var conteudoRetorno = streamReaderResponse.ReadToEnd();
var retornoXml = new XmlDocument();
try
{
retornoXml.LoadXml(conteudoRetorno);
}
catch (XmlException ex)
{
if (webException != null)
{
throw (webException);
}
throw (ex);
}
catch (Exception ex)
{
throw (ex);
}
if (soap.TagRetorno.ToLower() != "prop:innertext")
{
var tagRetorno = soap.TagRetorno;
if (soap.TipoAmbiente == TipoAmbiente.Homologacao && !string.IsNullOrWhiteSpace(soap.TagRetornoHomologacao))
{
tagRetorno = soap.TagRetornoHomologacao;
}
if (retornoXml.GetElementsByTagName(tagRetorno)[0] == null)
{
throw new Exception("Não foi possível localizar a tag <" + tagRetorno + "> no XML retornado pelo webservice.\r\n\r\n" +
"Conteúdo retornado pelo servidor:\r\n\r\n" +
retornoXml.InnerXml);
}
if (TratarScapeRetorno)
{
RetornoServicoString = retornoXml.GetElementsByTagName(tagRetorno)[0].ChildNodes[0].InnerText;
}
else
{
RetornoServicoString = retornoXml.GetElementsByTagName(tagRetorno)[0].ChildNodes[0].OuterXml;
}
}
else
{
if (string.IsNullOrWhiteSpace(retornoXml.InnerText))
{
throw new Exception("A propriedade InnerText do XML retornado pelo webservice está vazia.");
}
RetornoServicoString = retornoXml.InnerText;
//Remover do XML retornado o conteúdo <?xml version="1.0" encoding="utf-8"?> ou gera falha na hora de transformar em XmlDocument
if (RetornoServicoString.IndexOf("?>") >= 0)
{
RetornoServicoString = RetornoServicoString.Substring(RetornoServicoString.IndexOf("?>") + 2);
}
//Remover quebras de linhas
RetornoServicoString = RetornoServicoString.Replace("\r\n", "");
}
if (soap.PadraoNFSe == PadraoNFSe.FIORILLI || soap.PadraoNFSe == PadraoNFSe.SONNER || soap.PadraoNFSe == PadraoNFSe.SMARAPD || soap.PadraoNFSe == PadraoNFSe.DSF)
{
RetornoServicoString = RetornoServicoString.Replace("ns1:", string.Empty);
RetornoServicoString = RetornoServicoString.Replace("ns2:", string.Empty);
RetornoServicoString = RetornoServicoString.Replace("ns3:", string.Empty);
RetornoServicoString = RetornoServicoString.Replace("ns4:", string.Empty);
}
else if (soap.PadraoNFSe == PadraoNFSe.SIMPLE)
{
RetornoServicoString = RetornoServicoString.Replace("m:", string.Empty);
}
RetornoServicoXML = new XmlDocument
{
PreserveWhitespace = false
};
RetornoServicoXML.LoadXml(RetornoServicoString);
}
我评论了原来的catch来找到问题,但我没有任何运气。
这是第一个参数的
Xmldocument.OuterXml
:
<?xml version="1.0" encoding="utf-8"?>
<consStatServNFCom versao="1.00" xmlns="http://www.portalfiscal.inf.br/nfcom">
<tpAmb>2</tpAmb>
<xServ>STATUS</xServ>
</consStatServNFCom>
这是 Servico 对象(WebString Soap):
Web URL = http://www.portalfiscal.inf.br/nfcom/wsdl/NFComStatusServico
Content Type = application/soap+xml; charset=utf-8;
Return Tag = nfcomResultMsg
Soap String = <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><nfcomDadosMsg xmlns="http://www.portalfiscal.inf.br/nfcom/wsdl/NFComStatusServico">{xmlBody}</nfcomDadosMsg></soap:Body></soap:Envelope>
我试图研究这个问题,但我读到的所有内容都是形式,至少是三年前的,并且有其他我没有问题的原因。
我仍在观看 IAmTimCorey 的视频,学习 C# 并尝试找出如何找到问题。我看到的最后一个视频是关于处理异常并帮助我使用我不知道的 StackTrace 和 InnerExeption。
起初我认为,也许是我的公共配置出了问题,所以,我在笔记本电脑上安装了 IIS(来自 Windows 功能)来尝试模拟错误,但没有成功。
我还阅读了有关 IIS、HttpWebRequest 和我的研究中显示的其他方法的 Microsoft 文档,但我无法弄清楚 IIS 环境和 HttpWebRequest 问题之间的关系。
这是我的
web.config
内容。除了 stdoutLogEnable 为 true 之外,此错误不会生成任何日志。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\NFeModelo62Api.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
<!--ProjectGuid: 4c7ebfbf-36d8-47ca-bc46-a62f36c09fa6-->
在仅使用我遇到问题的服务从头开始重新制作 API 后,我找到了解决方案。我决定创建一个简单的场景来调查这个问题。
在遇到其他一些问题之后,我终于在临时服务器的应用程序文件夹中遇到了之前的相同错误:
无法确定重定向的 https 端口。
dotnet-wtrace
我在 Stack Overflow 帖子中找到了解决方案无法确定重定向的 https 端口
C:\inetpub\wwwcore\NFComModelo62\> dotnet-wtrace --handlers aspnet .\NFeModelo62Api.exe http://localhost/NFeModelo62Getway/v1/getStatus62
更改为
Load User Profile
。我显示了下面的打印屏幕,但我的 Windows 不是英文,仅供参考。