Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.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# NET核心与.NET框架中HTTP上的SOAPAction_C#_.net_Soap_.net Core_Httpwebrequest - Fatal编程技术网

C# NET核心与.NET框架中HTTP上的SOAPAction

C# NET核心与.NET框架中HTTP上的SOAPAction,c#,.net,soap,.net-core,httpwebrequest,C#,.net,Soap,.net Core,Httpwebrequest,我在旧的应用程序中有以下代码: // send request HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "text/xml;charset=UTF-8"; req.Method = "POST"; req.Accept = "text/xml"; req.Headers.Add(Ht

我在旧的应用程序中有以下代码:

        //  send request
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.ContentType = "text/xml;charset=UTF-8";
        req.Method = "POST";
        req.Accept = "text/xml";
        req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
        req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

        var test = req.Headers.ToString();

        if (string.IsNullOrWhiteSpace(SOAPaction))
            req.Headers.Add("SOAPAction", "\"\"");
        else
            req.Headers.Add("SOAPAction", "\"" + SOAPaction + "\"");

        using (var writer = new StreamWriter(req.GetRequestStream(), Encoding.UTF8))
        {
            xdoc.Save(writer, SaveOptions.DisableFormatting);
        }

        WebResponse response;
        try
        {
            response = req.GetResponse();

            System.Diagnostics.Debug.WriteLine(response.ToString());
        }
        catch (WebException we)
        {
            if (we.Response.ContentType.StartsWith("text/xml", StringComparison.InvariantCultureIgnoreCase))
            {
                using (var stream = we.Response.GetResponseStream())
                {
                    var xml = XDocument.Load(stream);
                    var fault = xml.Descendants().FirstOrDefault(e => e.Name.LocalName == "faultstring").Value;
                    throw new Exception("Error received when invoking the method: " + fault);
                }
            }
            else
                throw we;
        }

我正试图将其移植到一个新的.NET核心应用程序,但在更改必要的头之后,我总是会收到错误:“远程服务器返回了一个错误:(500)内部服务器错误”,这并没有什么帮助。我知道HttpWebRequest在.NET Framework和.NET Core中的工作方式有所不同,但在.NET Core中设置了头之后,它应该会进行相同的调用,我想?

我不确定服务器为什么会拒绝它,因为我觉得您的请求代码很好。
(500)内部服务器错误是服务器端错误。大多数情况下,它来自于请求主体、标题或url本身,服务器拒绝了它。因此,您需要从url开始调试。我发现有时必须在url末尾指定
?WSDL
,如果未指定,它将返回
500内部服务器错误
。所以,先检查一下这个。如果问题仍然存在,请检查正文并在测试工具(如
SoapUI
Postman
)上进行测试,确保它使用的内容和标题与您在请求中使用的内容和标题相同

另外,我建议改为移动到
HttpClient
(因为它已经被移动到了,如果可能的话。因为
HttpWebRequest
是一个死区。
HttpClient
是建立在它之上的,它比传统的
HttpWebRequest
更好,也更易于维护(另外它是用
async
开箱即用的方式构建的)

如果您坚持使用
HttpWebRequest
,那么您可以实现自己的类,这将使维护更容易。我已经为我以前的项目专门为Soap API及其信封构建了一个小而基本的类。因为我不想在每个类似的项目上重写相同的内容。我希望它会有用:

Soap API类

public class SoapAPI : IDisposable
{
    // Requirements for Soap API 
    private const string SoapAction = "SOAPAction";
    private const string SoapContentType = "text/xml;charset=\"utf-8\"";
    private const string SoapAccept = "text/xml";
    private const string SoapMethod = "POST";

    private HttpWebRequest _request;

    private SoapEnvelope _soapEnvelope;

    public class SoapAPIResponse
    {
        private readonly SoapAPI _instance;

        public SoapAPIResponse(SoapAPI instance)
        {
            _instance = instance;
        }
        public HttpWebResponse AsWebResponse()
        {
            try
            {
                _instance.SendRequest(_instance._soapEnvelope.GetEnvelope());

                return (HttpWebResponse)_instance._request.GetResponse();
            }
            catch (WebException ex)
            {
                throw ex;
            }

        }

        public StreamReader AsStreamReader()
        {
            return new StreamReader(AsHttpWebResponse().GetResponseStream());
        }

        public string AsString()
        {
            return AsStreamReader().ReadToEnd();
        }
    }

    public SoapAPI(string url, SoapEnvelope envelope)
    {
        if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(nameof(url)); }

        if (envelope == null) { throw new ArgumentNullException(nameof(envelope)); }

        // some Soap Services requires to target the xml schema ?wsdl at the end of the url, just uncomment if needed. 
        // url = url.LastIndexOf("?WSDL", StringComparison.InvariantCultureIgnoreCase) > 0 ? url : $"{url}?WSDL";

        _request = (HttpWebRequest)WebRequest.Create(new Uri(url));

        _request.Headers.Clear();

        _request.Headers.Add(SoapAction, envelope.SoapActionName);

        _request.ContentType = SoapContentType;

        _request.Accept = SoapAccept;

        _request.Method = SoapMethod;

        // optimizations 
        _request.ServicePoint.ConnectionLimit = 8;
        _request.Proxy = null;
        _request.KeepAlive = true;
        _request.ReadWriteTimeout = 300000;

        // envelope
        _soapEnvelope = envelope;
    }

    public SoapAPI AddHeader(string name, string value)
    {
        _request.Headers.Add(name, value);
        return this;
    }

    public SoapAPI AddHeader(HttpRequestHeader header, string value)
    {
        _request.Headers.Add(header, value);
        return this;
    }

    public SoapAPI AddCompressionMethod(DecompressionMethods methods)
    {
        _request.AutomaticDecompression = methods;
        return this;
    }

    private void SendRequest(object obj)
    {
        using StreamWriter sw = new StreamWriter(_request.GetRequestStream(), Encoding.UTF8);
        sw.Write(obj);
    }

    public SoapAPIResponse GetResponse()
    {
        return new SoapAPIResponse(this);
    }



    #region IDisposable

    private bool _disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }


    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _request = null;
                _soapEnvelope = null;
            }

            _disposed = true;
        }
    }


    ~SoapAPI()
    {
        Dispose(false);
    }

    #endregion

}
SoapEnvelope类

public class SoapEnvelope : IDisposable
{
    private XDocument _envelope;

    public XNamespace SoapNamespace = "http://schemas.xmlsoap.org/soap/envelope/";

    public XNamespace SoapActionNamespace { get; }

    public string SoapActionName { get; }

    public SoapEnvelope(XNamespace actionNamespace, string actionName)
    {
        if (actionNamespace == null) { throw new ArgumentNullException(nameof(actionNamespace)); }

        if (string.IsNullOrEmpty(actionName)) { throw new ArgumentNullException(nameof(actionName)); }

        SoapActionNamespace = actionNamespace;
        SoapActionName = actionName;
        CreateEnvelope();
    }

    private void CreateEnvelope()
    {
        _envelope = new XDocument(
            new XElement(SoapNamespace + "Envelope",
            new XAttribute(XNamespace.Xmlns + "soapenv", SoapNamespace),
            new XAttribute(XNamespace.Xmlns + SoapActionName, SoapActionNamespace),
            new XElement(SoapNamespace + "Header"),
            new XElement(SoapNamespace + "Body")
            )
         );
    }

    public SoapEnvelope AddHeaderElement(XElement elements)
    {
        _envelope.Root.Element(SoapNamespace + "Header").Add(elements);
        return this;
    }

    public SoapEnvelope AddBodyElement(XElement elements)
    {
        _envelope.Root.Element(SoapNamespace + "Body").Add(elements);
        return this;
    }

    public XDocument GetEnvelope()
    {
        return _envelope;
    }

    public bool IsValidXml(string xml)
    {
        try
        {
            XmlConvert.VerifyXmlChars(xml);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    #region IDisposable

    private bool _disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }


    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _envelope = null;
                SoapNamespace = null;
            }

            _disposed = true;
        }
    }


    ~SoapEnvelope()
    {
        Dispose(false);
    }

    #endregion
}
以下是基本用法:

WebResponse response; // will hold the response. 

XNamespace actionNamespace = "http://xxxx"; // the namespace 
var SoapAction = ""; //the action value  

var envelope = 
    new SoapEnvelope(actionNamespace, SoapAction)
        .AddBodyElement(new XElement(...)); 

using (var request = new SoapAPI(url, envelope))
{
    response = request
    .AddCompressionMethod(DecompressionMethods.GZip | DecompressionMethods.Deflate)
    .AddHeader(HttpRequestHeader.AcceptEncoding, "gzip,deflate")
    .GetResponse()
    .AsWebResponse(); // you can get the respnse as StreamReader, WebResponse, and String 
}

查看服务器日志以了解有关500的更多详细信息。如果不可用,请检查innerexception和客户端的其他异常详细信息。ssl?“tls客户端版本”?我无法访问服务器日志。innerexception为null,客户端SecurityProtocol设置为SecurityProtocolType.Tls12。这是在.NET F上手动完成的框架应用程序,在.NET Core中可以工作并且应该是默认的,但是当我手动设置它时,它不会改变任何东西。尝试添加:req.ProtocolVersion=HttpVersion.Version10;如果它是旧代码,它可能使用http 1.0,而不是默认的http 1.1。这不起作用。我还在.NET Framework中的旧版本/工作版本中尝试了它给出版本10和版本11的正确响应