Я не уверен, почему сервер отклонил его, так как ваш код запроса мне подходит. (500) Internal Server Error
- ошибка на стороне сервера. В основном это от тела запроса или заголовков или самого URL, сервер отклонил его. Поэтому вам нужно начать отладку, начиная с URL. Я обнаружил, что иногда обязательно указывать ?WSDL
в конце URL-адреса, если он не указан, он возвращает 500 internal server error
. Итак, сначала проверьте это. если проблема все еще существует, проверьте тело и протестируйте его на инструменте тестирования, таком как SoapUI
или Postman
, убедитесь, что он работает с тем же контентом и заголовками, которые вы используете в запросе.
Кроме того, я бы предложил вместо этого перейти к HttpClient
(поскольку он был перемещен в, если это возможно. Поскольку HttpWebRequest
является мертвой зоной. HttpClient
построен поверх нее, и это было бы лучше и проще в обслуживании, чем устаревшая HttpWebRequest
(плюс она построена с async
из коробки).
Если вы застряли с HttpWebRequest
, то вы можете реализовать свой собственный класс, который облегчит обслуживание. Я создал небольшой базовый класс c специально для 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
}
вот базовое c использование:
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
}