Удаленный сервер возвратил ошибку 417 expectation failed

This same situation and error can also arise with a default wizard generated SOAP Web Service proxy (not 100% if this is also the case on the WCF System.ServiceModel stack) when at runtime:

  • the end user machine is configured (in the Internet Settings) to use a proxy that does not understand HTTP 1.1
  • the client ends up sending something that a HTTP 1.0 proxy doesnt understand (commonly an Expect header as part of a HTTP POST or PUT request due to a standard protocol convention of sending the request in two parts as covered in the Remarks here)

… yielding a 417.

As covered in the other answers, if the specific issue you run into is that the Expect header is causing the problem, then that specific problem can be routed around by doing a relatively global switching off of the two-part PUT/POST transmission via System.Net.ServicePointManager.Expect100Continue.

However this does not fix the complete underlying problem — the stack may still be using HTTP 1.1 specific things such as KeepAlives etc. (though in many cases the other answers do cover the main cases.)

The actual problem is however that the autogenerated code assumes that it’s OK to go blindly using HTTP 1.1 facilities as everyone understands this. To stop this assumption for a specific Web Service proxy, one can change override the default underlying HttpWebRequest.ProtocolVersion from the default of 1.1 by creating a derived Proxy class which overrides protected override WebRequest GetWebRequest(Uri uri) as shown in this post:-

public class MyNotAssumingHttp11ProxiesAndServersProxy : MyWS
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
      HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
      request.ProtocolVersion = HttpVersion.Version10;
      return request;
    }
}

(where MyWS is the proxy the Add Web Reference wizard spat out at you.)


UPDATE: Here’s an impl I’m using in production:

class ProxyFriendlyXXXWs : BasicHttpBinding_IXXX
{
    public ProxyFriendlyXXXWs( Uri destination )
    {
        Url = destination.ToString();
        this.IfProxiedUrlAddProxyOverriddenWithDefaultCredentials();
    }

    // Make it squirm through proxies that don't understand (or are misconfigured) to only understand HTTP 1.0 without yielding HTTP 417s
    protected override WebRequest GetWebRequest( Uri uri )
    {
        var request = (HttpWebRequest)base.GetWebRequest( uri );
        request.ProtocolVersion = HttpVersion.Version10;
        return request;
    }
}

static class SoapHttpClientProtocolRealWorldProxyTraversalExtensions
{
    // OOTB, .NET 1-4 do not submit credentials to proxies.
    // This avoids having to document how to 'just override a setting on your default proxy in your app.config' (or machine.config!)
    public static void IfProxiedUrlAddProxyOverriddenWithDefaultCredentials( this SoapHttpClientProtocol that )
    {
        Uri destination = new Uri( that.Url );
        Uri proxiedAddress = WebRequest.DefaultWebProxy.GetProxy( destination );
        if ( !destination.Equals( proxiedAddress ) )
            that.Proxy = new WebProxy( proxiedAddress ) { UseDefaultCredentials = true };
    }
}

This same situation and error can also arise with a default wizard generated SOAP Web Service proxy (not 100% if this is also the case on the WCF System.ServiceModel stack) when at runtime:

  • the end user machine is configured (in the Internet Settings) to use a proxy that does not understand HTTP 1.1
  • the client ends up sending something that a HTTP 1.0 proxy doesnt understand (commonly an Expect header as part of a HTTP POST or PUT request due to a standard protocol convention of sending the request in two parts as covered in the Remarks here)

… yielding a 417.

As covered in the other answers, if the specific issue you run into is that the Expect header is causing the problem, then that specific problem can be routed around by doing a relatively global switching off of the two-part PUT/POST transmission via System.Net.ServicePointManager.Expect100Continue.

However this does not fix the complete underlying problem — the stack may still be using HTTP 1.1 specific things such as KeepAlives etc. (though in many cases the other answers do cover the main cases.)

The actual problem is however that the autogenerated code assumes that it’s OK to go blindly using HTTP 1.1 facilities as everyone understands this. To stop this assumption for a specific Web Service proxy, one can change override the default underlying HttpWebRequest.ProtocolVersion from the default of 1.1 by creating a derived Proxy class which overrides protected override WebRequest GetWebRequest(Uri uri) as shown in this post:-

public class MyNotAssumingHttp11ProxiesAndServersProxy : MyWS
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
      HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
      request.ProtocolVersion = HttpVersion.Version10;
      return request;
    }
}

(where MyWS is the proxy the Add Web Reference wizard spat out at you.)


UPDATE: Here’s an impl I’m using in production:

class ProxyFriendlyXXXWs : BasicHttpBinding_IXXX
{
    public ProxyFriendlyXXXWs( Uri destination )
    {
        Url = destination.ToString();
        this.IfProxiedUrlAddProxyOverriddenWithDefaultCredentials();
    }

    // Make it squirm through proxies that don't understand (or are misconfigured) to only understand HTTP 1.0 without yielding HTTP 417s
    protected override WebRequest GetWebRequest( Uri uri )
    {
        var request = (HttpWebRequest)base.GetWebRequest( uri );
        request.ProtocolVersion = HttpVersion.Version10;
        return request;
    }
}

static class SoapHttpClientProtocolRealWorldProxyTraversalExtensions
{
    // OOTB, .NET 1-4 do not submit credentials to proxies.
    // This avoids having to document how to 'just override a setting on your default proxy in your app.config' (or machine.config!)
    public static void IfProxiedUrlAddProxyOverriddenWithDefaultCredentials( this SoapHttpClientProtocol that )
    {
        Uri destination = new Uri( that.Url );
        Uri proxiedAddress = WebRequest.DefaultWebProxy.GetProxy( destination );
        if ( !destination.Equals( proxiedAddress ) )
            that.Proxy = new WebProxy( proxiedAddress ) { UseDefaultCredentials = true };
    }
}

Ошибка 417 Expectation Failed

Ошибка 417 Expectation Failed говорит о том, что сервер, к которому обращается клиент, мне может обработать поле Expect. Второй вариант: при обращении через прокси сервер время ожидание истекло.

Ошибка 417 во втором варианте прямо перекликается с ошибкой 408, когда соединение разорвано при отсутствии ответа. Только в отношении ошибки 417 явно использование прокси-сервера, чего нет в ошибке 408.

Кто сталкивается с проблемой и причины ее появления

Появляется ошибка 417 Expectation Failed чаще всего при использовании профессиональных программ, которые требуют соединение с сетью. К таким программам можно отнести 1С и другие. Т.е. обычно такой сбой может обнаружить системный администратор при настройке сервера или соединения программ в единую сеть.

Другая категория – обычные пользователи. Чаще всего обращаются с такой проблемой любители поиграть. Если игра лицензионная и проверяется через сеть, должны быть открыты определенные порты для активации и проверки лицензии.

Сбои могут происходить ввиду невозможности программой поддерживать формат HTTP 1.1, которые работают по методу Post. Это также касается программ, которые используют старый, Богом не признанный, Internet Explorer.

  1. Если вы используете прокси сервер Squid, вы однозначно получите ошибку HTTP 417, т.к. Squid не поддерживает заголовки HTTP1. обработка таких запросов происходит по методу Post, поэтому чтобы решить проблему, достаточно в конфигурацию прокси сервера Squid прописать:

ignore_expect_100 on

  1. В случае использования игры или программы с проверкой лицензии, нужно убедиться, что у вас на руках есть эта самая лицензия. При условии, что вы используете не совсем лицензионный метод активации, скорее всего нужно поставить блокировку доступа к сети в файле hosts. В случае, когда с лицензией слава Богу все в порядке, нужно сбросить настройки роутера к заводским. Если этот вариант не сработал, подключаемся по кабелю. Когда и этот вариант возвращает ошибку 417 – звоним провайдеру и уточняем, работают ли они с прокси и открыты ли у них порты 80 или 443. При этом, когда предыдущие варианты вы выполнили, а эффект тот же – вопросы к провайдеру.
  2. В случае использования ИЕ (Internet Explorer) в настройках нужно включить использование HTTP1. В таком случае ошибка 417 Expectation Failed можно решить, если сервис, программа обращается через этот формат.
  3. При использовании онлайн-лицензии возможна ошибка «Удаленный сервер возвратил ошибку: 417 Expectation Failed». Обычно это возникает ввиду неправильной обработки строки Expect: 100-Continue» со стороны прокси сервера. Что делать? В первом пункте вы найдете строчку кода, которую нужно поставить в конфигурационном файле.
  4. Если в настройках есть пункт «Подключение в обход прокси-сервера», включите его, это моментально решит ваши проблемы.
  5. Обратите внимание, что ошибка 417 может появляется в результате работы фильтра прокси-сервера, который блокирует протокол “Soap over HTTP’.

Практически во всех случаях, когда появляется ошибка 417 Expectation Failed виноват прокси-сервер. Вариантов решения несколько. Выше мы указали варианты решения, как для администраторов, так и для простых пользователей. Если у вас ситуация, которую не удается решить, напишите о ней в форме комментариев ниже и прикрепите скриншот. Наш технический специалист постарается вам помочь. НО! Огромная просьба — пишите развернуто, мы не прорицатели и не можем увидеть название софта, систему и т.д.

Дальше по теме…

Вопрос:

Возникают ошибки следующего вида:

Удаленный сервер возвратил ошибку: (417) Expectation failed.

Ответ:

Ошибка «(417) Expectation failed» может возникнуть из-за неправильной обработки поля «Expect: 100-Continue» вашим прокси-сервером.

Попробуйте в файл <папка_c_Business_Studio>PingServicePing.Service.config, в секцию <configuration>, добавить следующие строки:

<system.net> 
  <settings>
    <servicePointManager expect100Continue="false"> 
  </settings>
</system.net>

и перезапустить службу BS_PingHost.

Примечание: данное исправление включено в Business Studio версии 4.0.4888 и выше (версия файла службы BS_PingHost – 2.0.4888 и выше)

Если это не поможет, то, данная несовместимость не может быть устранена на клиентской стороне. Варианты решения:

  • В остальных случаях – разрешить службе BS_PingHost доступ в Интернет в обход прокси-сервера.

Возможно также, что прокси-сервер имеет фильтр, блокирующий протокол «SOAP over HTTP».

This same situation and error can also arise with a default wizard generated SOAP Web Service proxy (not 100% if this is also the case on the WCF System.ServiceModel stack) when at runtime:

  • the end user machine is configured (in the Internet Settings) to use a proxy that does not understand HTTP 1.1
  • the client ends up sending something that a HTTP 1.0 proxy doesnt understand (commonly an Expect header as part of a HTTP POST or PUT request due to a standard protocol convention of sending the request in two parts as covered in the Remarks here)

… yielding a 417.

As covered in the other answers, if the specific issue you run into is that the Expect header is causing the problem, then that specific problem can be routed around by doing a relatively global switching off of the two-part PUT/POST transmission via System.Net.ServicePointManager.Expect100Continue.

However this does not fix the complete underlying problem — the stack may still be using HTTP 1.1 specific things such as KeepAlives etc. (though in many cases the other answers do cover the main cases.)

The actual problem is however that the autogenerated code assumes that it’s OK to go blindly using HTTP 1.1 facilities as everyone understands this. To stop this assumption for a specific Web Service proxy, one can change override the default underlying HttpWebRequest.ProtocolVersion from the default of 1.1 by creating a derived Proxy class which overrides protected override WebRequest GetWebRequest(Uri uri) as shown in this post:-

public class MyNotAssumingHttp11ProxiesAndServersProxy : MyWS
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
      HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
      request.ProtocolVersion = HttpVersion.Version10;
      return request;
    }
}

(where MyWS is the proxy the Add Web Reference wizard spat out at you.)


UPDATE: Here’s an impl I’m using in production:

class ProxyFriendlyXXXWs : BasicHttpBinding_IXXX
{
    public ProxyFriendlyXXXWs( Uri destination )
    {
        Url = destination.ToString();
        this.IfProxiedUrlAddProxyOverriddenWithDefaultCredentials();
    }

    // Make it squirm through proxies that don't understand (or are misconfigured) to only understand HTTP 1.0 without yielding HTTP 417s
    protected override WebRequest GetWebRequest( Uri uri )
    {
        var request = (HttpWebRequest)base.GetWebRequest( uri );
        request.ProtocolVersion = HttpVersion.Version10;
        return request;
    }
}

static class SoapHttpClientProtocolRealWorldProxyTraversalExtensions
{
    // OOTB, .NET 1-4 do not submit credentials to proxies.
    // This avoids having to document how to 'just override a setting on your default proxy in your app.config' (or machine.config!)
    public static void IfProxiedUrlAddProxyOverriddenWithDefaultCredentials( this SoapHttpClientProtocol that )
    {
        Uri destination = new Uri( that.Url );
        Uri proxiedAddress = WebRequest.DefaultWebProxy.GetProxy( destination );
        if ( !destination.Equals( proxiedAddress ) )
            that.Proxy = new WebProxy( proxiedAddress ) { UseDefaultCredentials = true };
    }
}

400 — Bad Request (Некорректный запрос)

«Плохой запрос». Этот ответ означает, что сервер не понимает… Читать далее

Подробнее

401 — Unauthorized (Не авторизован)

«Неавторизовано». Для получения запрашиваемого ответа нужна … Читать далее

Подробнее

402 — Payment Required (Необходима оплата)

«Необходима оплата». Этот код ответа зарезервирован для буду… Читать далее

Подробнее

403 — Forbidden (Запрещено)

«Запрещено». У клиента нет прав доступа к содержимому, поэто… Читать далее

Подробнее

404 — Not Found (Не найдено)

«Не найден». Сервер не может найти запрашиваемый ресурс. Код… Читать далее

405 — Method Not Allowed (Метод не поддерживается)

«Метод не разрешен». Сервер знает о запрашиваемом методе, но… Читать далее

Подробнее

406 — Not Acceptable (Неприемлемо)

Этот ответ отсылается, когда веб сервер после выполнения ser… Читать далее

Подробнее

407 — Proxy Authentication Required (Необходима аутентификация прокси)

Этот код ответа аналогичен коду 401, только аутентификация т… Читать далее

Подробнее

408 — Request Timeout (Истекло время ожидания)

Ответ с таким кодом может прийти, даже без предшествующего з… Читать далее

Подробнее

409 — Conflict (Конфликт)

Этот ответ отсылается, когда запрос конфликтует с текущим со… Читать далее

Подробнее

410 — Gone (Удалён)

Этот ответ отсылается, когда запрашиваемый контент удален с … Читать далее

Подробнее

411 — Length Required (Необходима длина)

Запрос отклонен, потому что сервер требует указание заголовк… Читать далее

412 — Precondition Failed (Условие ложно)

Клиент указал в своих заголовках условия, которые сервер не … Читать далее

Подробнее

413 — Request Entity Too Large (Полезная нагрузка слишком велика)

Размер запроса превышает лимит, объявленный сервером. Сервер… Читать далее

Подробнее

414 — Request-URI Too Long (URI слишком длинный)

URI запрашиваемый клиентом слишком длинный для того, чтобы с… Читать далее

Подробнее

415 — Unsupported Media Type (Неподдерживаемый тип данных)

Медиа формат запрашиваемых данных не поддерживается сервером… Читать далее

Подробнее

416 — Requested Range Not Satisfiable (Диапазон не достижим)

Диапозон указанный заголовком запроса Range не может бы… Читать далее

Подробнее

417 — Expectation Failed (Ожидание не удалось)

Этот код ответа означает, что ожидание, полученное из заголо… Читать далее

Подробнее

418 — I’m a teapot (Я — чайник)

I’m a teapot — Этот код был введен в 1998 году как одна из т… Читать далее

419 — Authentication Timeout (not in RFC 2616) (Обычно ошибка проверки CSRF)

Authentication Timeout (not in RFC 2616) — Этого кода нет в … Читать далее

Подробнее

420 — Enhance Your Calm (Twitter) (Подождите немного (Твиттер))

Возвращается Twitter Search и Trends API, когда клиент отпра… Читать далее

Подробнее

421 — Misdirected Request (Неверный запрос)

Misdirected Request — запрос был перенаправлен на сервер, не… Читать далее

Подробнее

422 — Unprocessable Entity (Необрабатываемый экземпляр)

Запрос имел правильный формат, но его нельзя обработать из-з… Читать далее

Подробнее

423 — Locked (Заблокировано)

Целевой ресурс из запроса заблокирован от применения к нему … Читать далее

Подробнее

424 — Failed Dependency (Невыполненная зависимость)

Не удалось завершить запрос из-за ошибок к предыдущем запрос… Читать далее

Подробнее

425 — Too Early (Слишком рано)

Too Early — сервер не готов принять риски обработки «ранней … Читать далее

426 — Upgrade Required (Необходимо обновление)

Указание сервера, клиенту, обновить протокол. Заголовок отве… Читать далее

Подробнее

428 — Precondition Required (Необходимо предусловие)

Precondition Required — сервер указывает клиенту на необходи… Читать далее

Подробнее

429 — Too Many Requests (Слишком много запросов)

Too Many Requests — клиент попытался отправить слишком много… Читать далее

Подробнее

430 — Would Block (Будет заблокировано)

Код состояния 430 would Block — это код, который сервер мог … Читать далее

Подробнее

431 — Request Header Fields Too Large (Поля заголовка запроса слишком большие)

Request Header Fields Too Large — Превышена допустимая длина… Читать далее

Подробнее

434 — Requested host unavailable (Запрашиваемый адрес недоступен)

Сервер к которому вы обратились недоступен… Читать далее

Подробнее

444 — No Response (Nginx) (Нет ответа (Nginx))

Код ответа Nginx. Сервер не вернул информацию и закрыл соеди… Читать далее

449 — Retry With (Повторить с…)

Retry With — возвращается сервером, если для обработки запро… Читать далее

Подробнее

450 — Blocked by Windows Parental Controls (Microsoft) (Заблокировано родительским контролем Windows (Microsoft))

Расширение Microsoft. Эта ошибка возникает, когда родительск… Читать далее

Подробнее

451 — Unavailable For Legal Reasons (Недоступно по юридическим причинам)

Unavailable For Legal Reasons — доступ к ресурсу закрыт по ю… Читать далее

Подробнее

499 — Client Closed Request (Клиент закрыл соединение)

Нестандартный код состояния, представленный nginx для случая… Читать далее

Подробнее

some minutes ago i was working on a project in visual studio 2010 and suddenly my pc was restarted.
after rebooting i got the error below when browsing that web site in local machine:

The request failed with HTTP status 417: Expectation Failed.

Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The request failed with
HTTP status 417: Expectation Failed.

my web site’s name is : MyWebSite
i have a web service on a remote server (a vps) that MyWebSite is using it and that error is in relationship with it.

Line 172:        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/MyWebSiteEnable", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
Line 173:        public bool MyWebSiteEnable() {
Line 174:            object[] results = this.Invoke("MyWebSiteEnable", new object[0]);
Line 175:            return ((bool)(results[0]));
Line 176:        }

every thing is ok about that web service.
so what is this error and how can i fix it?
there is just a simple bool method inside that web service that returns true.
and i am using that web servive in code-behind like below :

private void CheckForPageExpiration()
{
    MyService service = new MyService();
    if (service.MyWebSiteEnable())
    {
    }
    else
    {
        Response.Redirect("~/blank.aspx");
    }
}

i removed that web service and add it again, but still have that error!
what is wrong about that?

thanks in advance

some minutes ago i was working on a project in visual studio 2010 and suddenly my pc was restarted.
after rebooting i got the error below when browsing that web site in local machine:

The request failed with HTTP status 417: Expectation Failed.

Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The request failed with
HTTP status 417: Expectation Failed.

my web site’s name is : MyWebSite
i have a web service on a remote server (a vps) that MyWebSite is using it and that error is in relationship with it.

Line 172:        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/MyWebSiteEnable", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
Line 173:        public bool MyWebSiteEnable() {
Line 174:            object[] results = this.Invoke("MyWebSiteEnable", new object[0]);
Line 175:            return ((bool)(results[0]));
Line 176:        }

every thing is ok about that web service.
so what is this error and how can i fix it?
there is just a simple bool method inside that web service that returns true.
and i am using that web servive in code-behind like below :

private void CheckForPageExpiration()
{
    MyService service = new MyService();
    if (service.MyWebSiteEnable())
    {
    }
    else
    {
        Response.Redirect("~/blank.aspx");
    }
}

i removed that web service and add it again, but still have that error!
what is wrong about that?

thanks in advance

i’m writing windows 8 app.(on Visiual Studio 2012) which uses my wcf service. It works well when i try at my home, so it can connect to the wcf. But when i tried at my office, it cannot connect to wcf and returns error :

The remote server returned an error: (417) Expectation Failed.

I think its causing by firewall in the office network..
Googled too much, tried a lot of however the problem still here.

System.Net.ServicePointManager.Expect100Continue = false;

Doesn’t work because .Net Framework 4.5 has not ServicePointManager Class but msdn says there is ServicePointManager on .Net 4.5..
http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.expect100continue.aspx

<system.net>
    <settings>
        <servicePointManager expect100Continue="false" />
    </settings>
</system.net>

Cannot try this to write on web.config or app.config because win8 app has not these files..

some people wrote above code to devenv.exe.config file of VS 2012. I tried it but nothing changed.

http://www.jlpaonline.com/?p=176

leppie's user avatar

leppie

114k17 gold badges194 silver badges295 bronze badges

asked Oct 3, 2012 at 6:50

Ateş Danış's user avatar

1

Well, you posted the question here, and Can Bilgin gave an answer.
I post it here for those who have the problem than you.

I think it should be possible to add the header manually… I would
give it a go with the operationscope… from an earlier example:

Task<GetADGroupMemberResponse> AccountManagement.GetADGroupMemberAsync(GetADGroupMemberRequest request)
{
    // CB: Creating the OperationContext
    using (var scope = new OperationContextScope(this.InnerChannel))
    {
        // CB: Creating and Adding the request header
        var header = MessageHeader.CreateHeader("Server", "http://schemas.microsoft.com/2008/1/ActiveDirectory/CustomActions", request.Server);
        OperationContext.Current.OutgoingMessageHeaders.Add(header);

        return base.Channel.GetADGroupMemberAsync(request);
    }
}

cause on the http requests with the httpclient you can do something
like (again from an earlier example):

var httpClient = new HttpClient(); 
var httpContent = new HttpRequestMessage(HttpMethod.Post, "http://app.proceso.com.mx/win8/login");

// NOTE: Your server was returning 417 Expectation failed, 
// this is set so the request client doesn't expect 100 and continue.
httpContent.Headers.ExpectContinue = false;

var values = new List<KeyValuePair<string, string>>(); 
values.Add(new KeyValuePair<string, string>("user", "******"));
values.Add(new KeyValuePair<string, string>("pass", "******"));

httpContent.Content = new FormUrlEncodedContent(values);

HttpResponseMessage response = await httpClient.SendAsync(httpContent);

// here is the hash as string 
var result = await response.Content.ReadAsStringAsync();

answered Nov 15, 2012 at 8:35

Nate B.'s user avatar

Nate B.Nate B.

94211 silver badges31 bronze badges

For reference, the following is a full example of using WebClient to post a JSON request to a REST webservice. It sets the Expect100Continue flag to false, includes proxy authentication using default credentials if required, and catches non-200 response codes.

void Main()
{
    var ms = new MemoryStream();
    var ser = new DataContractJsonSerializer(typeof(Job));
    ser.WriteObject(ms, new Job { Comments = "Test", Title = "TestTitle", Id = 1 });

    var uri = new Uri("http://SomeRestService/Job");
    var servicePoint = ServicePointManager.FindServicePoint(uri);
    servicePoint.Expect100Continue = false;

    var webClient = new WebClient();
    webClient.Headers["Content-type"] = "application/json";

    IWebProxy defaultProxy = WebRequest.DefaultWebProxy;
    if (defaultProxy != null){
        defaultProxy.Credentials = CredentialCache.DefaultCredentials;
        webClient.Proxy = defaultProxy;
    }

    try {
        var result = webClient.UploadData(uri, "POST", ms.ToArray());
    } catch (WebException we) {
        var response = (HttpWebResponse)we.Response;
    }
}

[DataContract]
public class Job
{
    [DataMember (Name="comments", EmitDefaultValue=false)]
    public string Comments { get; set; }
    [DataMember (Name="title", EmitDefaultValue=false)]
    public string Title { get; set; }
    [DataMember (Name="id", EmitDefaultValue=false)]
    public int Id { get; set; }
}

answered Mar 11, 2014 at 23:11

David Clarke's user avatar

David ClarkeDavid Clarke

12.8k9 gold badges87 silver badges111 bronze badges

Although adding this line
()
as a setting to the config may fix the initial error you are likely to still get (504) Gateway Timeout if your proxy settings are not allowing you to use the correct open port open to your on the target server. To add a proxy exception for the server you are sending to, add it via internet explorer as a proxy exclusion on connections tab -> LAN settings -> Advanced. I hope you’ll be able to connect then.

answered Nov 25, 2014 at 13:58

MrTea's user avatar

MrTeaMrTea

961 gold badge1 silver badge9 bronze badges

i’m writing windows 8 app.(on Visiual Studio 2012) which uses my wcf service. It works well when i try at my home, so it can connect to the wcf. But when i tried at my office, it cannot connect to wcf and returns error :

The remote server returned an error: (417) Expectation Failed.

I think its causing by firewall in the office network..
Googled too much, tried a lot of however the problem still here.

System.Net.ServicePointManager.Expect100Continue = false;

Doesn’t work because .Net Framework 4.5 has not ServicePointManager Class but msdn says there is ServicePointManager on .Net 4.5..
http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.expect100continue.aspx

<system.net>
    <settings>
        <servicePointManager expect100Continue="false" />
    </settings>
</system.net>

Cannot try this to write on web.config or app.config because win8 app has not these files..

some people wrote above code to devenv.exe.config file of VS 2012. I tried it but nothing changed.

http://www.jlpaonline.com/?p=176

leppie's user avatar

leppie

114k17 gold badges194 silver badges295 bronze badges

asked Oct 3, 2012 at 6:50

Ateş Danış's user avatar

1

Well, you posted the question here, and Can Bilgin gave an answer.
I post it here for those who have the problem than you.

I think it should be possible to add the header manually… I would
give it a go with the operationscope… from an earlier example:

Task<GetADGroupMemberResponse> AccountManagement.GetADGroupMemberAsync(GetADGroupMemberRequest request)
{
    // CB: Creating the OperationContext
    using (var scope = new OperationContextScope(this.InnerChannel))
    {
        // CB: Creating and Adding the request header
        var header = MessageHeader.CreateHeader("Server", "http://schemas.microsoft.com/2008/1/ActiveDirectory/CustomActions", request.Server);
        OperationContext.Current.OutgoingMessageHeaders.Add(header);

        return base.Channel.GetADGroupMemberAsync(request);
    }
}

cause on the http requests with the httpclient you can do something
like (again from an earlier example):

var httpClient = new HttpClient(); 
var httpContent = new HttpRequestMessage(HttpMethod.Post, "http://app.proceso.com.mx/win8/login");

// NOTE: Your server was returning 417 Expectation failed, 
// this is set so the request client doesn't expect 100 and continue.
httpContent.Headers.ExpectContinue = false;

var values = new List<KeyValuePair<string, string>>(); 
values.Add(new KeyValuePair<string, string>("user", "******"));
values.Add(new KeyValuePair<string, string>("pass", "******"));

httpContent.Content = new FormUrlEncodedContent(values);

HttpResponseMessage response = await httpClient.SendAsync(httpContent);

// here is the hash as string 
var result = await response.Content.ReadAsStringAsync();

answered Nov 15, 2012 at 8:35

Nate B.'s user avatar

Nate B.Nate B.

94211 silver badges31 bronze badges

For reference, the following is a full example of using WebClient to post a JSON request to a REST webservice. It sets the Expect100Continue flag to false, includes proxy authentication using default credentials if required, and catches non-200 response codes.

void Main()
{
    var ms = new MemoryStream();
    var ser = new DataContractJsonSerializer(typeof(Job));
    ser.WriteObject(ms, new Job { Comments = "Test", Title = "TestTitle", Id = 1 });

    var uri = new Uri("http://SomeRestService/Job");
    var servicePoint = ServicePointManager.FindServicePoint(uri);
    servicePoint.Expect100Continue = false;

    var webClient = new WebClient();
    webClient.Headers["Content-type"] = "application/json";

    IWebProxy defaultProxy = WebRequest.DefaultWebProxy;
    if (defaultProxy != null){
        defaultProxy.Credentials = CredentialCache.DefaultCredentials;
        webClient.Proxy = defaultProxy;
    }

    try {
        var result = webClient.UploadData(uri, "POST", ms.ToArray());
    } catch (WebException we) {
        var response = (HttpWebResponse)we.Response;
    }
}

[DataContract]
public class Job
{
    [DataMember (Name="comments", EmitDefaultValue=false)]
    public string Comments { get; set; }
    [DataMember (Name="title", EmitDefaultValue=false)]
    public string Title { get; set; }
    [DataMember (Name="id", EmitDefaultValue=false)]
    public int Id { get; set; }
}

answered Mar 11, 2014 at 23:11

David Clarke's user avatar

David ClarkeDavid Clarke

12.8k9 gold badges87 silver badges111 bronze badges

Although adding this line
()
as a setting to the config may fix the initial error you are likely to still get (504) Gateway Timeout if your proxy settings are not allowing you to use the correct open port open to your on the target server. To add a proxy exception for the server you are sending to, add it via internet explorer as a proxy exclusion on connections tab -> LAN settings -> Advanced. I hope you’ll be able to connect then.

answered Nov 25, 2014 at 13:58

MrTea's user avatar

MrTeaMrTea

961 gold badge1 silver badge9 bronze badges

Вопрос:

Возникают ошибки следующего вида:

Удаленный сервер возвратил ошибку: (417) Expectation failed.

Ответ:

Ошибка «(417) Expectation failed» может возникнуть из-за неправильной обработки поля «Expect: 100-Continue» вашим прокси-сервером.

Попробуйте в файл <папка_c_Business_Studio>PingServicePing.Service.config, в секцию <configuration>, добавить следующие строки:

<system.net> 
  <settings>
    <servicePointManager expect100Continue="false"> 
  </settings>
</system.net>

и перезапустить службу BS_PingHost.

Примечание: данное исправление включено в Business Studio версии 4.0.4888 и выше (версия файла службы BS_PingHost – 2.0.4888 и выше)

Если это не поможет, то, данная несовместимость не может быть устранена на клиентской стороне. Варианты решения:

  • В остальных случаях – разрешить службе BS_PingHost доступ в Интернет в обход прокси-сервера.

Возможно также, что прокси-сервер имеет фильтр, блокирующий протокол «SOAP over HTTP».

We’re trying to connect from a Backendservice made with NET Core 3.1 to a legacy WCF Service. For this we use the two NuGet packages «System.ServiceModel.Http» and «System.ServiceModel.Primitives» (latest version 4.8.1).

For the connection to the endpoint we create the binding/serviceclient manual as follows

var binding = new BasicHttpsBinding();

binding.Security.Mode = BasicHttpsSecurityMode.Transport;
binding.Security.Transport = new HttpTransportSecurity() { ClientCredentialType = HttpClientCredentialType.Certificate, ProxyCredentialType = HttpProxyCredentialType.Basic };
binding.CloseTimeout = new TimeSpan(0, 12, 0, 0, 0);
binding.OpenTimeout = new TimeSpan(0, 12, 0, 0, 0);
binding.SendTimeout = new TimeSpan(0, 12, 0, 0, 0);
binding.MaxReceivedMessageSize = 2147483646;
binding.MaxBufferSize = 2147483646;

var channelfactory = new SearchServiceClient(binding, endpoint);
channelfactory.ClientCredentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName, "CERTIFICATENAME");

var response = await channelfactory.existsAsync(...);

In order to establish the connection we need to use an SSL client certificate, not a username/password.

With each request we receive the following error message: «The remote server returned an error: (417) Expectation Failed».

I did some research and found out that all you need to do is set the «ExpectContinue» flag to false.

Unfortunately this does not work via the ServicePointManager (not even in web.config).

ServicePointManager.Expect100Continue = false;

if I downgrade the nuget package version of «System.ServiceModel.Http» and «System.ServiceModel.Primitives» to 4.4.4, it works.

Does anyone know how I can do this with the latest version ?

  • Удаление ошибок абс тойота
  • Удаленный рабочий стол код ошибки 0x516
  • Удаленный сервер возвратил ошибку 413 request entity too large
  • Удаление ошибки подушки безопасности ниссан кашкай
  • Удаленный рабочий стол код ошибки 0x4