- Remove From My Forums
-
Question
-
Hello all..
I have builded a soap request.. but it’s still not working, can some one help me out..?
Error:
System.Net.WebException: The remote server returned an error: (400) Bad Request. at System.Net.HttpWebRequest.GetResponse() at CallReportsConsole.MainClass.Main(String[] args) in C:**ConsoleProgram.cs:line 57 The remote server returned an error: (400) Bad Request. Code:
using System; using System.Net; using System.IO; using System.Text; using System.Xml; namespace CallReportsConsole { class MainClass { public static void Main(string[] args) { try { int username = 123456; string password = «wachtwoord»; //Create SOAP XML StringBuilder sbSoap = new StringBuilder(); //1. Build SOAP string sbSoap.Append(«<? xml version=»1.0″ encoding=»utf-8″ ?>«); sbSoap.Append(«<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/»>n»); sbSoap.Append(«<soap:Body>n»); sbSoap.Append(» <GetProductSpecifications xmlns=»http://www.bascomputers.nl/»>n»); sbSoap.Append(«<customerID>» + username + «</customerID>n»); sbSoap.Append(«<password>» + password + «</password>n»); sbSoap.Append(«</GetProductSpecifications>n»); sbSoap.Append(«</soap:Body></soap:Envelope>«); string soapAction = «http://www.bascomputers.nl/GetProductSpecifications»; //2. Send XML to CDR server string cdrURL = «http://xtract.bascomputers.nl:4040/xtract.asmx»; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(cdrURL); req.ContentType = «text/xml; charset=utf-8»; req.Accept = «text/xml»; req.Method = «POST»; req.ContentLength = sbSoap.Length; req.Headers.Add(«SOAPAction», soapAction); req.KeepAlive = false; Stream strm = req.GetRequestStream(); byte[] bytes = System.Text.Encoding.ASCII.GetBytes(sbSoap.ToString()); strm.Write(bytes, 0, bytes.Length); strm.Close(); //3. Get response & send back filename HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); StreamReader r = new StreamReader(resp.GetResponseStream()); XmlTextReader xmlRead = new XmlTextReader(r); while (xmlRead.Read()) { Console.Write(xmlRead.Value.ToString()); } r.Close(); strm.Close(); } catch (WebException wex) { Console.Write(wex.ToString()); Console.Write(wex.Message.ToString()); } catch (Exception ex) { Console.Write(ex.ToString()); Console.Write(ex.Message.ToString()); } Console.Read(); } } }
Answers
-
Use the following code. try
{ string soapRequest= «<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/’>» + «n» + «<soap:Body> » + «n» + «<m:GetProductSpecifications xmlns:m=‘http://www.bascomputers.nl/’>» + «n» + «<m:customerID>123456</m:customerID>«+ «n» + «<m:password>wachtwoord</m:password>» + «n» + «</m:GetProductSpecifications>» + «n» + «</soap:Body>» + «n» + «</soap:Envelope>» + «n» ; string soapAction = «http://www.bascomputers.nl/GetProductSpecifications»; //2. Send XML to CDR server string cdrURL = «http://xtract.bascomputers.nl:4040/xtract.asmx»; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(cdrURL); req.ContentType = «text/xml; charset=utf-8»; req.Accept = «text/xml»; req.Method = «POST»; //req.ContentLength = sbSoap.Length; req.Headers.Add(«SOAPAction», soapAction); req.KeepAlive = false; XmlDocument doc = new XmlDocument(); doc.LoadXml(soapRequest); using (Stream strm = req.GetRequestStream()) { doc.Save(strm); } //XmlDocument doc = new XmlDocument(); // doc.LoadXML(soapRequest); //3. Get response & send back filename HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //StreamReader r = new //StreamReader(resp.GetResponseStream()); using (Stream respStm = resp.GetResponseStream()) { using (StreamReader r = new StreamReader(respStm)) { string str = r.ReadToEnd(); } } }
Be Happy
-
Marked as answer by
Tuesday, February 10, 2009 12:51 PM
-
Marked as answer by
Exchange Server 2019 Exchange Server 2016 Exchange Server 2013 Еще…Меньше
Проблемы
При попытке запросить сведения о занятости пользователя в другом лесу доверенного перекрестного топологии запрос не справился с запросом и создает следующее сообщение об ошибке:
-
MessageText: «При обнаружении не удалось найти адрес электронной почты user@domain.com с ошибкой Майкрософт. Exchange.InfoWorker.Common.Availability.AutoDiscoverFailedException: удаленный сервер возвращает ошибку (400) Bad Request.. Сведения о запросе: URL-адрес обнаружения : https:// targetdomain.com/Autodiscover/Autodiscover.xml, EmailAddress : <user>SMTP:user@ targetdomain.com. —> System.Net.WebException: удаленный сервер возвращает ошибку (400) Bad Request.
на сайте System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
-
в корпорации Майкрософт. Exchange.InfoWorker.Common.Availability.AutoDiscoverRequest.EndInvoke(IAsyncResult asyncResult)
— конце внутренней трассировки стека исключений —
Причина
Это известная проблема в обновлении системы безопасности за апрель 2021 г. и май 2021 г. для Microsoft Exchange Server 2019, 2016 и 2013 гг.
Обходное решение
Чтобы обойти эту проблему, воспользуйтесь одним из следующих способов:
Способ 1
Не используйте учетную запись службы при настройке адресного пространства доступности. Чтобы настроить адресное пространство, выполните указанные здесь действия.
-
Создайте учетную запись <targetdomain><fbaccount>» в целевом лесу.
Примечание. Это может быть обычная учетная запись пользователя. Почтовый ящик не требуется.
-
Предоставление разрешений для новой учетной записи в целевом лесу:
-
set-AvailabilityConfig -PerUserAccount <targetdomain><fbaccount>
-
-
В лесу источника удалите существующее адресное пространство доступности:
-
remove-AvailabilityAddressSpace <ID of the AvailabilityAddressSpace of Target domain>
-
-
Добавьте новое адресное пространство доступности. В этот раз-UseServiceAccount$falseи использовать параметр -Credentials :
-
Add-AvailabilityAddressSpace -ForestName <Target Forest Name> -AccessMethod PerUserFB -UseServiceAccount $false -Credentials (Get-Credential)
-
-
Когда вам будет предложено ввести учетные данные, введите учетные данные для targetdomainfbaccount.
-
Перезапустите службы IIS IIS, выпустив следующий cmdlet PowerShell:
-
Restart-Service W3SVC, WAS
Способ 2
-
Настройте федераированный общий доступ между Exchange организации.
-
Перезапустите службы IIS IIS, выпустив следующий cmdlet PowerShell:
-
Restart-Service W3SVC, WAS
Ссылки
Настройка федератного общего доступа Exchange организации | Документы Майкрософт
Описание обновления для системы безопасности Microsoft Exchange Server 2019, 2016 и 2013 г.: 13 апреля 2021 г. (KB5001779)
Нужна дополнительная помощь?
|
Shiryaev 0 / 0 / 0 Регистрация: 25.11.2014 Сообщений: 11 |
||||
|
1 |
||||
|
02.09.2020, 17:11. Показов 4993. Ответов 8 Метки нет (Все метки)
Добрый день, друзья. Пытаюсь написать небольшое приложение, чтобы сохранить некоторые фотографии с сайта https://pastvu.com/. Уже в начале потерпел неудачу в виде ошибки от сервера: 400 — Недопустимый запрос. Планируется небольшое автоматическое редактирование фотографий, поэтому и использую Win.Forms.
Я так думаю, ошибка имеет фундаментальный характер, так-как всего пять строчек кода написано. Но я упорно не могу найти решение в гугле. Может быть конкретно в этом случае C# и WebClient неподходящие технологии или что-то ещё использовать нужно? Пожалуйста, кто знает, подскажите в каком направлении искать решение
__________________
0 |
|
796 / 579 / 207 Регистрация: 21.02.2019 Сообщений: 2,095 |
|
|
02.09.2020, 17:41 |
2 |
|
.. если недопустимый запрос, то, возможно, сервер ждет определенных заголовков в запросе (таких, как в запросе из браузера) … вот тут посмотрите, как добавить заголовки к запросу:
1 |
|
0 / 0 / 0 Регистрация: 25.11.2014 Сообщений: 11 |
|
|
02.09.2020, 18:36 [ТС] |
3 |
|
carrotik, Статью посмотрел, попробовал разные заголовки подобавлять — толку нет. Попробовал «надурочка» атрибут http-equiv HTML тега<meta> в коде страницы посмотреть и добавить из него содержимое — тоже не вышло. Есть ли способ узнать какие заголовки сервер хочет?
0 |
|
2931 / 2101 / 611 Регистрация: 02.08.2011 Сообщений: 5,799 |
|
|
02.09.2020, 18:55 |
4 |
|
толку нет И User-Agent тоже не помогает?
1 |
|
2931 / 2101 / 611 Регистрация: 02.08.2011 Сообщений: 5,799 |
|
|
02.09.2020, 18:57 |
5 |
|
Вот что Chrome отправляет: Миниатюры
1 |
|
2931 / 2101 / 611 Регистрация: 02.08.2011 Сообщений: 5,799 |
|
|
02.09.2020, 18:58 |
6 |
|
Можете поиграться.
1 |
|
Shiryaev 0 / 0 / 0 Регистрация: 25.11.2014 Сообщений: 11 |
||||
|
02.09.2020, 20:22 [ТС] |
7 |
|||
|
IamRain, carrotik, Собственно заголовок User-Agent помог. По сути добавил строку
Прямо со скриншота переписал данные. Текст страницы получил, покопался в нём и взгрустнул. Судя по всему, основной контент страницы генерируется javascript`ом и очевидным для меня методом фотографии не скачать, ибо ссылок нет. Может быть можно как-то яваскрипт выполнить, но это явно не в этой теме обсуждать надо. Буду думать, может и ручками всё сохраню.
0 |
|
484 / 439 / 123 Регистрация: 05.01.2010 Сообщений: 1,848 |
|
|
02.09.2020, 20:51 |
8 |
|
Shiryaev, на странице с конкретной фотографией в meta есть строки вида
1 |
|
0 / 0 / 0 Регистрация: 25.11.2014 Сообщений: 11 |
|
|
02.09.2020, 22:08 [ТС] |
9 |
|
valera_21, Да, это так. Но я хотел сохранить все фотографии конкретных городов, а для этого нужно именно с той злополучной страницы работу начинать. Можно было бы по другому пойти, допустим тупо по всем ссылкам пройтись (например, начать условно с https://pastvu.com/p/0, а закончить https://pastvu.com/p/9999999) и в описании фотографий искать нужный город, но описание так же с помощью скрипта генерируется, как я понял. Улица и название фотографии в тегах есть, а города не вижу Добавлено через 8 минут
0 |
Я пытаюсь отправить SMS из своего веб-приложения. Я использую сторонний веб-сервис для отправки сообщений. В среде разработки я могу отправлять SMS, когда то же самое приложение, размещенное в рабочей среде, получает следующую ошибку:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
--- End of inner exception stack trace
Server stack trace:
at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Ниже приведены изменения, которые я сделал в файле web.config:
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
<basicHttpBinding>
<binding name="IBulkSMS" closeTimeout="00:10:00" openTimeout="00:10:00"
receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="500000" maxBufferPoolSize="524288" maxReceivedMessageSize="500000"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="10500" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
<endpoint address="SMS.asmx"
binding="basicHttpBinding" bindingConfiguration="IBulkSMS"
contract="IBulkSMS.IBulkSMS" name="IBulkSMS" >
<identity>
<servicePrincipalName value="host/MachineName" />
</identity>
</endpoint>
- Remove From My Forums
-
Question
-
Hi,
I have a created a wcf webservice that has a method that takes a base64string and a string as parameters. When I call the method I get the following error:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
I have done some research and found that the reason for the error might be that the base64string is to large (155412). I don’t have any max values set in the Web config file at the moment. Can someone help me with what parameters I need to set and to what?
Also, do I need to set the same parameters to the same values in the web.config for the client as well?
Kind Regards
Cecilia
Answers
-
Have you tried setting the MaxRecievedMessageSize quota on your binding to a high enough number? Also, as a debugging technique, you may want to turn on tracing to see what’s happening inside the service. The following config for your service will enable diagnostic tracing:
<configuration>
<system.diagnostics>
<sources>
<source name=«System.ServiceModel« switchValue=«Warning«>
<listeners>
<add name=«_listener0« />
</listeners>
</source>
</sources>
<sharedListeners>
<add name=«_listener0« type=«System.Diagnostics.XmlWriterTraceListener«
initializeData=«MyTraceFile.e2e« traceOutputOptions=«Callstack« />
</sharedListeners>
<trace autoflush=«true« />
</system.diagnostics>
….
svcTraceViewer will enable you to view the traces.
- Remove From My Forums
-
Question
-
Hi,
I have a created a wcf webservice that has a method that takes a base64string and a string as parameters. When I call the method I get the following error:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
I have done some research and found that the reason for the error might be that the base64string is to large (155412). I don’t have any max values set in the Web config file at the moment. Can someone help me with what parameters I need to set and to what?
Also, do I need to set the same parameters to the same values in the web.config for the client as well?
Kind Regards
Cecilia
Answers
-
Have you tried setting the MaxRecievedMessageSize quota on your binding to a high enough number? Also, as a debugging technique, you may want to turn on tracing to see what’s happening inside the service. The following config for your service will enable diagnostic tracing:
<configuration>
<system.diagnostics>
<sources>
<source name=«System.ServiceModel« switchValue=«Warning«>
<listeners>
<add name=«_listener0« />
</listeners>
</source>
</sources>
<sharedListeners>
<add name=«_listener0« type=«System.Diagnostics.XmlWriterTraceListener«
initializeData=«MyTraceFile.e2e« traceOutputOptions=«Callstack« />
</sharedListeners>
<trace autoflush=«true« />
</system.diagnostics>
….
svcTraceViewer will enable you to view the traces.


