0

I am given a config file that contains the endpoint address, username, and password. I am told to write a method to call this soap endpoint, but after a few hours of research, I still can not put the pieces together. Please see below for the config file.

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="Username" value="username"/>
        <add key="Password" value="password"/>
    </appSettings>
    <system.serviceModel>
        <bindings>
            <customBinding>
                <binding name="SecureBinding">
                    <textMessageEncoding messageVersion="Soap11"/>
                    <security authenticationMode="UserNameOverTransport" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" enableUnsecuredResponse="true"/>
                    <httpsTransport/>
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="https://xxxxxxxxxxxx/ExecutePortType" binding="customBinding" bindingConfiguration="SecureBinding" contract="com.company.ExecutePortType" name="ExecutePortType"/>
        </client>
        <extensions>
            <bindingElementExtensions>
                <add name="customTextMessageEncoding" type="WsSecurityMessageEncoder.CustomTextMessageEncodingElement, WsSecurityMessageEncoder"/>
            </bindingElementExtensions>
        </extensions>
    </system.serviceModel>
    <system.web>
        <compilation debug="true" targetFramework="4.6"/>
    </system.web>
</configuration>

I keep getting

The remote server returned an error: (401) Unauthorized.

And this is what I have in my code so far. A lot of it I copied and pasted from this link

private readonly Uri _Address;
private readonly string _Username;
private readonly string _Password;
public KeyReaderRepository()
{

    _Username = Environment.ExpandEnvironmentVariables(ConfigurationManager.AppSettings["naServiceUserName"]);
    _Password = Environment.ExpandEnvironmentVariables(ConfigurationManager.AppSettings["naServicePassword"]);
    var KeyreaderUrl = Environment.ExpandEnvironmentVariables(ConfigurationManager.AppSettings["KeyreaderEndpoint"]);
    _Address = new Uri(KeyreaderUrl);
}
public string DecryptKeyReader()
{
    XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
    HttpWebRequest webRequest = CreateWebRequest();
    //InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
    Stream stream = webRequest.GetRequestStream();
    soapEnvelopeXml.Save(stream);

    // begin async call to web request.
    IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

    //// suspend this thread until call is complete. You might want to
    //// do something usefull here like update your UI.
    //asyncResult.AsyncWaitHandle.WaitOne();

    // get the response from the completed web request.
    string soapResult;
    using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
    {
        using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
        {
            soapResult = rd.ReadToEnd();
        }
        Console.Write(soapResult);
    }

    return "";
}

private HttpWebRequest CreateWebRequest()
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_Address);
    webRequest.Headers.Add("SOAPAction", "");
    webRequest.ContentType = "application/soap+xml;charset=UTF-8";
    webRequest.Accept = "text/xml";
    webRequest.Method = "POST";
    webRequest.Credentials = new NetworkCredential(_Username, _Password);
    return webRequest;
}

private static XmlDocument CreateSoapEnvelope()
{
    XmlDocument soapEnvelopeDocument = new XmlDocument();
    soapEnvelopeDocument.LoadXml(@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><HelloWorld xmlns=""http://tempuri.org/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><int1 xsi:type=""xsd:integer"">12</int1><int2 xsi:type=""xsd:integer"">32</int2></HelloWorld></SOAP-ENV:Body></SOAP-ENV:Envelope>");
    return soapEnvelopeDocument;
}

private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
    using (Stream stream = webRequest.GetRequestStream())
    {
        soapEnvelopeXml.Save(stream);
    }
}

Can someone please tell me what I'm doing wrong? Or what I'm missing? Thanks

Matt
  • 1,245
  • 2
  • 17
  • 32
Vibol
  • 615
  • 1
  • 8
  • 25
  • Please try to remove UseDefaultCredentials and PreAuthenticate. None example I have seen use these flags. – Sean Stayns Feb 12 '18 at 22:15
  • yeah that didn't work. The reason those two were there in the first place was because what i had before didnt work :P – Vibol Feb 12 '18 at 22:18
  • For round about 3 weeks, I have used this code from your link and it works fine! https://stackoverflow.com/a/44201422/5056173 (Answer with 4 upvotes, debiasej) I have removed the SOAP Header. – Sean Stayns Feb 12 '18 at 22:24
  • Giving you a ServiceModel config section is not enough to go on. You need documentation or a WSDL at least. – Crowcoder Feb 12 '18 at 22:58
  • @Crowcoder the WSDL doesnt exist. i checked :( – Vibol Feb 12 '18 at 23:04

1 Answers1

0

Have you checked, whether the _Username and _Password variable is set correctly?

Because you set the username and password in the config file:

<appSettings>
   <add key="Username" value="username"/>
   <add key="Username" value="password"/>
</appSettings>

I think you should change your file to:

<appSettings>
   <add key="Username" value="username"/>
   <add key="Password" value="password"/>        <------ Password instead of Username!?
</appSettings>
Sean Stayns
  • 4,082
  • 5
  • 25
  • 35