Ошибка проверки подлинности прокси-сервера при запуске кода во внутренней сети. Проблема с кодом? - PullRequest
1 голос
/ 04 мая 2011

Я написал тестовое приложение для проверки некоторых данных пользователя по внутренней службе RESTful.

Если я делаю запрос напрямую через браузер, я получаю ответ от службы, НО, если я делаю запрос через мой код, в ответе говорится, что мне нужна аутентификация прокси-сервера.

Хотя я мог предоставить настраиваемые пользователем параметры, чтобы можно было передавать параметры прокси-сервера, он просто кажется неправильным, и я не уверен, что мой код неверен.

Ниже приведен фрагмент кода, который завершается с ошибкой, а затем фрагмент с подробностями прокси.

/// <summary>
/// Validate the user details
/// </summary>
/// <returns>True if the user credentials are valid, else false</returns>
public bool ValidateUser()
{
    bool valid = false;

    try
    {
        // Create the XML to be passed as the request
        XElement root = BuildRequestXML("LOGON");

        // Add the action to the service address
        Uri serviceReq = new Uri(m_ServiceAddress + "?obj=LOGON");

        // Make the RESTful request to the service using a POST
        using (HttpResponseMessage response = new HttpClient().Post(serviceReq, HttpContentExtensions.CreateDataContract(itrent)))
        {
            // Retrieve the response for processing
            response.Content.LoadIntoBuffer();
            string returned = response.Content.ReadAsString();

            // TODO: parse the response string for the required data

        }
    }
    catch (Exception ex)
    {
        Log.WriteLine(Category.Serious, "Unable to validate the User details", ex);
        valid = false;
    }

    return valid;
}

Теперь для чанка, который работает, но имеет проблемы ...

/// <summary>
/// Validate the user details
/// </summary>
/// <returns>True if the user credentials are valid, else false</returns>
public bool ValidateUser()
{
    bool valid = false;

    try
    {
        // Create the XML to be passed as the request
        XElement root = BuildRequestXML("LOGON");

        // Add the action to the service address
        Uri serviceReq = new Uri(m_ServiceAddress + "?obj=LOGON");

        // Create the client for the request
        using (HttpClient client = new HttpClient())
        {

            // Create a proxy to get around the network issues and assign it to the http client
            WebProxy px = new WebProxy( <Proxy server address>, <Proxy Server Port> );
            px.Credentials = new NetworkCredential( <User Name>, <Password>, <Domain> );
            client.TransportSettings.Proxy = px;

            // Mare the RESTful request
            HttpResponseMessage response = client.Post(serviceReq, HttpContentExtensions.CreateDataContract(root));

            // Retrieve the response for processing
            response.Content.LoadIntoBuffer();
            string returned = response.Content.ReadAsString();

            // TODO: parse the response string for the required data

        }
    }
    catch (Exception ex)
    {
        Log.WriteLine(Category.Serious, "Unable to validate the User details", ex);
        valid = false;
    }

    return valid;
}

Все предложения принимаются с благодарностью. Приветствия.

Ответы [ 2 ]

3 голосов
/ 04 мая 2011

Когда вы заходите на сервис, вы используете настройки прокси для зарегистрированного пользователя. Когда вы пытаетесь пройти через прокси через веб-сервис, он, вероятно, работает как учетная запись ASP.NET, для которой не настроены параметры прокси.

Вы можете либо

  • Укажите настраиваемые параметры прокси, как вы предлагаете
  • Запустить веб-службу под учетной записью, для которой настроены правильные параметры прокси-сервера (возможно, с использованием проверки подлинности Windows?)
  • Попробуйте добавить раздел в ваш web.config <system.net> <defaultProxy useDefaultCredentials="true"> <proxy usesystemdefault="true"/> </defaultProxy> </system.net>

Хорошая дискуссия по этому вопросу здесь

0 голосов
/ 04 мая 2011

Поместите этот код в ваш app.config.Следует отключить прокси

<system.net> 
  <defaultProxy 
    enabled="false" 
    useDefaultCredentials="false" > 
    <proxy/> 
    <bypasslist/> 
    <module/> 
  </defaultProxy> 
</system.net> 
...