从C#REST API调用SOAP服务

时间:2018-10-03 14:32:02

标签: c# rest soap

我有一个VBA代码,该代码调用SOAP服务并接收XML响应。 我想编写一个C#REST API以类似的方式调用此SOAP服务。

在这里参考文章,我编写了一个SOAP请求,但是它不起作用,并返回以下错误。我可以从VBA代码以及POST MAN中调用此SOAP服务。有人可以解释一下我的代码有什么问题吗?

 public class CallSOAPAPIController : ApiController
{
    [HttpGet]
    public string Extract()
    {
        HttpWebRequest request = CreateWebRequest();
        XmlDocument soapEnvelopeXml = new XmlDocument();

        soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?><soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:inc=""http://www.test-xyz.com/""><soap:Body>Calendar @Year@Month@1</soap:Body></soap:Envelope>");

        using (Stream stream = request.GetRequestStream())
        {
            soapEnvelopeXml.Save(stream);
        }

        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader rd = new StreamReader(response.GetResponseStream()))
            {
                soapResult = rd.ReadToEnd();
                Console.WriteLine(soapResult);
            }
        }

        return soapResult;
    }

    /// <summary>
    /// Create a soap webrequest to [Url]
    /// </summary>
    /// <returns></returns>
    public static HttpWebRequest CreateWebRequest()
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http://test.production-xyz.com/listofemployees.do?getdetails=all&SOAP");

        webRequest.Headers.Add(@"SOAP:Action");
        webRequest.ContentType = "text/xml;charset=\"utf-8\"";
        webRequest.Accept = "text/xml";
        webRequest.Method = "POST";

        CallSOAPAPIController obj = new CallSOAPAPIController();

        string base64Credentials = obj.GetEncodedCredentials();
        webRequest.Headers.Add("Authorization", "Basic " + base64Credentials);

        return webRequest;
    }

    private string GetEncodedCredentials()
    {
        string m_Username = "XXXXXX";
        string m_Password = "XXXXXX";

        string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
        byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
        return Convert.ToBase64String(byteCredentials);
    }

}

我得到的错误是:“远程服务器返回了错误:(401)未经授权”

Unauthorized(401)

0 个答案:

没有答案
相关问题