Рефакторинг интерфейса для использования HttpWebRequest, который в настоящее время использует универсальный System.ServiceModel.ClientBase - PullRequest
1 голос
/ 01 ноября 2011

В настоящее время я работаю над рефакторингом интерфейса (службы Windows .net wcf), который отправляет данные в службу осей на основе Java.

Я бы хотел, чтобы новое резервирование могло отправлять фрагмент XMLиспользуя http веб-запрос к URL-адресу, который в данный момент сконфигурирован в app.config из интерфейса на основе wcf.

До сих пор я захватил протоколирование со старого интерфейса и создал новый интерфейс, способный опубликовать этоданные на URL.В основном это работает.Ответ от службы оси заключается в том, что токен не может быть проверен:

<faultstring>WSDoAllReceiver: security processing failed; 
nested exception is:    org.apache.ws.security.WSSecurityException: 
The security token could not be authenticated or authorized</faultstring>

В старом интерфейсе информация о привязке в app.config выглядит следующим образом:

  <endpoint address="https://beta.<<>>.com/ws/services/ReservationService"
    behaviorConfiguration="" binding="customBinding" bindingConfiguration="MutualCertificateBinding"
    contract="ReservationServiceContract" name="" kind="" endpointConfiguration="">
    <identity>
      <certificateReference x509FindType="FindByThumbprint" findValue="27 38 6f 86 b6 67 45 be 1a 60 60 ef 1f 7c 73 d6 5b 1b 7d 7f"
        isChainIncluded="false" />
    </identity>
  </endpoint>

Я использую следующий код для отправки запроса в веб-службу:

    private string HandleHttpPost(string url, UTF8Encoding encoding, string xmlMsg)
    {
        System.Net.ServicePointManager.Expect100Continue = false;

        string request = textBoxRequestPrefix.Text + xmlMsg;
        byte[] data = encoding.GetBytes(request);

        var webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = WebRequestMethods.Http.Post;
        webRequest.ContentType = textBoxRequestContentType.Text;

        if(!string.IsNullOrEmpty(textBoxSoapAction.Text))
            webRequest.Headers.Add("SOAPAction", textBoxSoapAction.Text);

        if (!string.IsNullOrEmpty(textBoxCertificatePath.Text))
        {
            X509Certificate2 xc = new X509Certificate2(textBoxCertificatePath.Text);
            webRequest.ClientCertificates.Add(xc);
        }

        Stream newStream = webRequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();

        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        Stream dataStream = webResponse.GetResponseStream();
        var reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();

        reader.Close();
        dataStream.Close();
        webResponse.Close();

        return responseFromServer;
    }

, который сообщает мне, что используется сертификат x509.У меня вопрос, как я могу заставить работать HttpWebRequest?

Дополнение: пользовательская конфигурация привязки:

<customBinding>
<binding name="MutualCertificateBinding" closeTimeout="00:05:00" openTimeout="00:05:00" sendTimeout="00:05:00">
  <security authenticationMode="UserNameOverTransport" securityHeaderLayout="Lax"
    includeTimestamp="false" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
    requireSignatureConfirmation="false">
    <secureConversationBootstrap />
  </security>
  <textMessageEncoding maxReadPoolSize="64" messageVersion="Soap11WSAddressing10" writeEncoding="utf-8">
    <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
  </textMessageEncoding>
  <context protectionLevel="None" />
  <httpsTransport maxBufferPoolSize="524288" maxReceivedMessageSize="65536" maxBufferSize="65536" />
</binding>
</customBinding>
...