System net webexception удаленный сервер возвратил ошибку 500

On reading your question I was suspicious this has to do with (or could be corrected by) setting the KeepAlive to false. Looking on SO — this question references the same problem and points to it as well: https://stackoverflow.com/a/2071374/1803682

Try setting:

request.KeepAlive = false;

With KeepAlive set to false your connection will be closed at the end of each request. If you are transmitting a lot of files this could be an issue — as it takes time to resend credentials, etc. The upside is you recreate the connection in a known / initial state which should solve your problem (even if it is not the root cause).

To see what is going on, if you can enable detailed logging on your server you should see the last command issued before seeing this error returned. This should give you a better idea of what is up. Found this thread saying much the same thing.

Update:

If I had read to the bottom of the link I posted myself I could have answered even better, the command probably being reissued is some part of the login process (i.e. USER username) and this is your likely issue:

The reason the creadentials may no longer be valid is that the
WebRequest uses a lease that expires after a certain amount of time.
If you don’t explicitly instantiate the lease and define its timeouts,
the FtpWebRequest appears to use default timeout values. I believe
what’s happening is that when the lease expires the FtpWebRequest will
then try to log on again.

So looking here with the right search:

yields that the default timeout waiting for requests is not infinite as specified but actually 10000 ms. Which seems a pretty big discrepancy. So you can also try setting:

request.Timeout = -1;

And see if it corrects your error.


Really don’t think this could be your issue so moving it to the bottom:

Also — check that your request.ReadWriteTimeout is appropriate for the speed you see for the larger file. The default is 5 minutes which would be pretty long for 290k, so I expect this is not the source of your error. Also — I would expect a connection closed error if this was the problem.

после обновление CU на Exchange 2013 перестали подключаться Outlook 2016
клиенты Outlook 2010, 2013 работают, OWA работает, новые 2016 — нет — постоянно запрашивает пароль (внутри сети и снаружи)
https*testconnectivity.microsoft.com сообщает:

Attempting to send an Autodiscover POST request to potential Autodiscover URLs.
Autodiscover settings weren't obtained when the Autodiscover POST request was sent.

Additional Details

Elapsed Time: 1952 ms.

Test Steps

The Microsoft Connectivity Analyzer is attempting to retrieve an XML Autodiscover response from URL https://autodiscover.mydomain.ru:443/Autodiscover/... for user derba@mydomain.ru.
The Microsoft Connectivity Analyzer failed to obtain an Autodiscover XML response.

Additional Details

An HTTP 500 response was returned from Unknown.
HTTP Response Headers:
request-id: 28560d3f-60a9-4d38-ba3e-9fe5d42aecc8
X-CalculatedBETarget: kvmail.mydomain.local
X-DiagInfo: KVMAIL
X-BEServer: KVMAIL
Cache-Control: private
Set-Cookie: ClientId=9QNDYXGKKVZALFBOSQ; expires=Wed, 25-Jul-2018 08:38:55 GMT; path=/; HttpOnly,X-BackEndCookie=S-1-5-21-1903798712-2405474663-4193718316-2295=u56Lnp2ejJqBz53IzJybxsrSxsfNntLLzsnG0sbJmczSzsyenMecyJqbzp2egYHNz87I0s/H0s3Lq8/HxczHxcrJ; expires=Thu, 24-Aug-2017 08:38:56 GMT; path=/Autodiscover; secure; HttpOnly
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
X-FEServer: KVMAIL
Date: Tue, 25 Jul 2017 08:38:55 GMT
Content-Length: 0
Elapsed Time: 1952 ms.

накатил CU 15 — не помогло … накатил CU 17 — не помогло.

все URL в виртуальных каталогах внешнего адреса mail.mydomain.ru , в DNS идет ссылка на внутренний сервер
mail.mydomain.ru 192.168.0.12
autodiscover.mydomain.ru 12.168.0.12
kvmail.mydomain.local 192.168.0.12

сертификат куплен, в нем прописан mail.mydomain.ru, сертификат весит на службах IIS, SMTP

пересоздавал все виртуальные каталоги 
делал наследование на пользователей домена (расширенные компоненты) 
в IIS на каталоги дал явно права на C:inetpubwwwroot пользователям «прошедшим проверку» на чтение и выполнение

при открытии https*192.168.0.12/Autodiscover/Autodiscover.xml (извне
тоже самое) запрашивает пароль, после ввода показывает:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
600Недопустимый запрос

переставлял IIS — не помогло.

[PS] C:>get-autodiscovervirtualdirectory | fl *path*
Выполняется создание нового сеанса для неявного удаленного взаимодействия команды "Get-AutodiscoverVirtualDirectory"...

MetabasePath : IIS://kvmail.mydomain.local/W3SVC/1/ROOT/Autodiscover
Path : C:Program FilesMicrosoftExchange ServerV15FrontEndHttpProxyAutodiscover

для пользователей «Прошедшие проверку» явно указал до папки C:Program FilesMicrosoftExchange ServerV15FrontEndHttpProxyAutodiscover права на чтение

[PS] C:>iisreset /noforce

Попытка остановки...
Службы Интернета успешно остановлены
Попытка запуска...
Службы Интернета успешно перезапущены
[PS] C:>Test-WebServicesConnectivity
Выполняется создание нового сеанса для неявного удаленного взаимодействия команды "Test-WebServicesConnectivity"...

Source ServiceEndpoint Scenario Result Latency
(MS)
------ --------------- -------- ------ -------
KVMAIL.domain.local autodiscover.mydomain.ru Автообнаружение: поставщик ... Failure 551
KVMAIL.domain.local EWS: GetFolder Skipped 0

[PS] C:>
[PS] C:>Test-WebServicesConnectivity | fl

RunspaceId : 6cf74bba-9812-4863-8641-88f1f3eeb753
Source : KVMAIL.domain.local
ServiceEndpoint : autodiscover.mydomain.ru
Scenario : AutoDiscoverSoapProvider
ScenarioDescription : Автообнаружение: поставщик SOAP
Result : Failure
Latency : 50
Error : System.Net.WebException: Удаленный сервер возвратил ошибку: (500) Внутренняя ошибка сервера.
в System.Net.HttpWebRequest.GetResponse()
в Microsoft.Exchange.Management.SystemConfigurationTasks.ServiceValidatorBase.InternalInvoke()
в Microsoft.Exchange.Management.SystemConfigurationTasks.ServiceValidatorBase.Invoke()
Verbose : [2017-07-25 22:06:20Z] Подключение Автообнаружение к "https://autodiscover.mydomain.ru/autodiscover/auto...".
[2017-07-25 22:06:20Z] Тестовая учетная запись: extest_91809daefd5e4@domain.local Пароль: ******
[2017-07-25 22:06:20Z] Запрос Автообнаружение:
User-Agent: KVMAIL/Test-WebServicesConnectivity/extest_91809daefd5e4@domain.local
Content-Type: text/xml; charset=utf-8
Authorization: Negotiate TlRMTVNTUAADAAAAGAAYAKoAAABkAWQBwgAAAAAAAABYAAAARABEAFgAAAAOAA4AnAAAABAAEAAmAgAAFYKI4gYDgCUAAAAP2jc/Z1olP4tXSSAeEc
AF8AOQAxADgAMAA5AGQAYQBlAGYAZAA1AGUANABAAG0AYQBnAGEAZABhAG4ALgBsAG8AYwBhAGwASwBWAFAATQBBAEkATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzGxPzJfeumcZ
ABIAiY/kgXTAT9/szZqaD2kAAAAAAIADgBNAEEARwBBAEQAQQBOAAEADgBLAFYAUABNAEEASQBMAAQAGgBtAGEAZwBhAGQAYQBuAC4AbABvAGMAYQBsAAMAKgBrAHYAcABtAGEAaQBs
EAbgAuAGwAbwBjAGEAbAAFABoAbQBhAGcAYQBkAGEAbgAuAGwAbwBjAGEAbAAHAAgASAImP5IF0wEGAAQAAgAAAAgAMAAwAAAAAAAAAAAAAAAAQAAAZB7M3pgHJN9JMYimsUzCsbO/A
KABAAx8wbQsBX7MrEx9zBcspCtAkAPgBIAFQAVABQAC8AYQB1AHQAbwBkAGkAcwBjAG8AdgBlAHIALgBtAGEAZwBhAGQAYQBuAGsAdgBwAC4AcgB1AAAAAAAAAAAAAAAAAEPe+B6G5X
Host: autodiscover.mydomain.ru
Cookie: ClientId=BEQIIQTUOFXWHNXSLG
Content-Length: 1149
Expect: 100-continue
[2017-07-25 22:06:20Z] Запрос Автообнаружение:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
Exchange2010schemas.microsoft.com/exchange/2010/Autodiscover/A...

[2017-07-25 22:06:20Z] Ответ Автообнаружение:
request-id: d3514bb0-2f8f-4a05-a0ab-b08652c42180
X-CalculatedBETarget: KVMAIL.domain.local
X-DiagInfo: KVMAIL
X-BEServer: KVMAIL
Persistent-Auth: true
X-FEServer: KVMAIL
Content-Length: 0
Cache-Control: private
Date: Tue, 25 Jul 2017 22:06:19 GMT
Set-Cookie: X-BackEndCookie=S-1-5-21-1903798712-2405474663-4193718316-2291=u56Lnp2ejJqBzJ6byMyZxszSxpvMyNLLzZzO0seax53Sx5qbnp3Pys6az8zMgYHN
/Jxc3P; expires=Thu, 24-Aug-2017 22:06:20 GMT; path=/autodiscover; secure; HttpOnly
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
[2017-07-25 22:06:20Z] Ответ Автообнаружение:
System.Net.WebException: Удаленный сервер возвратил ошибку: (500) Внутренняя ошибка сервера.
в System.Net.HttpWebRequest.GetResponse()
в Microsoft.Exchange.Management.SystemConfigurationTasks.ServiceValidatorBase.InternalInvoke()
в Microsoft.Exchange.Management.SystemConfigurationTasks.ServiceValidatorBase.Invoke()
MonitoringEventId : 6051

RunspaceId : 6cf74bba-9812-4863-8641-88f1f3eeb753
Source : KVMAIL.domain.local
ServiceEndpoint :
Scenario : EwsGetFolder
ScenarioDescription : EWS: GetFolder
Result : Skipped
Latency : 0
Error : Пропущено тестирование веб-служб Exchange из-за ошибки на шаге автообнаружения.
Verbose :
MonitoringEventId : 5053

logo424

35 / 25 / 13

Регистрация: 12.02.2011

Сообщений: 178

Записей в блоге: 1

1

18.11.2013, 23:24. Показов 7308. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Доброго времени, у меня проблема с запросом, а точней с кодом ответа..
200 — нормальный статус
500 — ошибка

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  public string post(string uri, string req)
    {
 
            string s = req;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.UserAgent = "Opera/9.80";
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] bytes = Encoding.ASCII.GetBytes(s);
            request.ContentLength = bytes.Length;
            request.GetRequestStream().Write(bytes, 0, bytes.Length);
            request.GetRequestStream().Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            statusCode = (int)response.StatusCode;
            return new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
 
      }

как только получаю 500
Высвечивается «webexception не обработано…»
Удаленный сервер возвратил ошибку: (500) Внутренняя ошибка сервера.
и подсвечивает эту часть
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

=====
Как решить можно?

Добавлено через 21 час 8 минут
эм есть кто знает?



0



Master of Orion

Эксперт .NET

6094 / 4950 / 905

Регистрация: 10.07.2011

Сообщений: 14,522

Записей в блоге: 5

19.11.2013, 10:34

2

logo424, берете программу fidler2 версии 4 и смотрите, что по факту отправляется
И не пишите все в одну строчку, у вас из-за этого куча временных объектов, не удаляемых сборщиком, висит



0



35 / 25 / 13

Регистрация: 12.02.2011

Сообщений: 178

Записей в блоге: 1

19.11.2013, 11:58

 [ТС]

3

Цитата
Сообщение от Psilon
Посмотреть сообщение

logo424, берете программу fidler2 версии 4 и смотрите, что по факту отправляется
И не пишите все в одну строчку, у вас из-за этого куча временных объектов, не удаляемых сборщиком, висит

у меня другой сниффер…
Я уже решил проблему



0



Master of Orion

Эксперт .NET

6094 / 4950 / 905

Регистрация: 10.07.2011

Сообщений: 14,522

Записей в блоге: 5

19.11.2013, 11:59

4

logo424, ну опишите тогда…



0



35 / 25 / 13

Регистрация: 12.02.2011

Сообщений: 178

Записей в блоге: 1

19.11.2013, 22:59

 [ТС]

5

Цитата
Сообщение от Psilon
Посмотреть сообщение

logo424, ну опишите тогда…

повторяю запрос если вылетела ошибка, try catch
у меня много запросов 1к+ и массив данных, так что мое повторение продолжает процесс а не обрывает



0



User-621232634 posted

Hello guys,

  I have the following error and I have no idea how to fix it. I tried but I couldn’t figure out the solution yet. Please if anyone can offer help, I would appreciate that.  

Server Error in '/' Application.

The remote server returned an error: (500) Internal Server Error. 
  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 remote server returned an error: (500) Internal Server Error.

Source Error: 



Line 105:            PostSoapClient oClient = new PostSoapClient();
Line 106:            oClient.Open();
Line 107:            HeritageCompany.wsPost.CreditCardResponse creditCardResponse = oClient.DoPost(creditCardRequest);
Line 108:            string response = "GatewayTransactionId: " + creditCardResponse.GatewayTxnId;
Line 109:            response = response + "tGatewayResponseCode: " + creditCardResponse.GatewayRspCode;
  

 Source File:  C:Usersmontadardocumentsvisual studio 2015ProjectsHeritageCompanyHeritageCompanyTest.aspx.cs    Line:  107 

Stack Trace: 



[WebException: The remote server returned an error: (500) Internal Server Error.]
   System.Net.HttpWebRequest.GetResponse() +1390
   System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +55

[ProtocolException: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '<!DOCTYPE html>
<html>
    <head>
        <title>Parser Error</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; ov'.]
   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +153
   System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336
   HeritageCompany.wsPost.PostSoap.DoPost(DoPostRequest request) +0
   HeritageCompany.wsPost.PostSoapClient.HeritageCompany.wsPost.PostSoap.DoPost(DoPostRequest request) +73
   HeritageCompany.wsPost.PostSoapClient.DoPost(CreditCardRequest creditCardRequest) +123
   HeritageCompany.Test.btnPost_Click(Object sender, EventArgs e) in C:Usersmontadardocumentsvisual studio 2015ProjectsHeritageCompanyHeritageCompanyTest.aspx.cs:107
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696754
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

 

Here is the code in C#: It throw an error and when it hits this line : HeritageCompany.wsPost.CreditCardResponse creditCardResponse = oClient.DoPost(creditCardRequest);

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.ServiceModel.Channels;
using HeritageCompany.wsPost;
namespace HeritageCompany
{
    public class Test : Page
    {
        protected HtmlForm form1;

        protected TextBox tbClientNumber;

        protected TextBox tbClientCode;

        protected TextBox tbAccountNumber;

        protected TextBox tbCardType;

        protected TextBox tbCardNumber;

        protected TextBox tbCVV2;

        protected TextBox tbExpiryMonth;

        protected TextBox tbExpiryYear;

        protected TextBox tbAmount;

        protected TextBox tbFirstName;

        protected TextBox tbLastName;

        protected TextBox tbAddress;

        protected TextBox tbCity;

        protected TextBox tbState;

        protected TextBox tbZipCode;

        protected TextBox tbUserData;

        protected TextBox tbUserID;

        protected Button btnPost;

        protected HtmlGenericControl spanResults;

        public IConfigurationSource configurationSource = null;

        public LogWriterFactory logWriterFactory = null;

        public LogWriter logWriter = null;

        protected void Page_Load(object sender, System.EventArgs e)
        {
        }

        public void InitializeLogger()
        {
            this.configurationSource = ConfigurationSourceFactory.Create();
            this.logWriterFactory = new LogWriterFactory(this.configurationSource);
            this.logWriter = this.logWriterFactory.Create();
        }

        public void LogMessage(string categories, string message, System.Diagnostics.TraceEventType traceEventType, int priority)
        {
            string[] a_Categories = categories.Split(new char[]
            {
                ','
            });
            LogEntry logEntry = new LogEntry();
            logEntry.Message = message;
            logEntry.Priority = priority;
            logEntry.Categories = a_Categories;
            logEntry.Severity = traceEventType;
            this.logWriter.Write(logEntry);
        }

        protected void btnPost_Click(object sender, System.EventArgs e)
        {
            HeritageCompany.wsPost.CreditCardRequest creditCardRequest = new HeritageCompany.wsPost.CreditCardRequest();
            creditCardRequest.ClientNumber = this.tbClientNumber.Text;
            creditCardRequest.ClientCode = this.tbClientCode.Text;
            creditCardRequest.AccountNumber = this.tbAccountNumber.Text;
            creditCardRequest.CardType = this.tbCardType.Text;
            creditCardRequest.CardNumber = this.tbCardNumber.Text;
            creditCardRequest.ExpiryMonth = this.tbExpiryMonth.Text;
            creditCardRequest.ExpiryYear = this.tbExpiryYear.Text;
            creditCardRequest.CVV2 = this.tbCVV2.Text;
            creditCardRequest.Amount = this.tbAmount.Text;
            creditCardRequest.FirstName = this.tbFirstName.Text;
            creditCardRequest.LastName = this.tbLastName.Text;
            creditCardRequest.Address = this.tbAddress.Text;
            creditCardRequest.City = this.tbCity.Text;
            creditCardRequest.State = this.tbState.Text;
            creditCardRequest.ZipCode = this.tbZipCode.Text;
            creditCardRequest.UserData = this.tbUserData.Text;
            creditCardRequest.UserID = this.tbUserID.Text;
            PostSoapClient oClient = new PostSoapClient();
            oClient.Open();
            HeritageCompany.wsPost.CreditCardResponse creditCardResponse = oClient.DoPost(creditCardRequest);
            string response = "GatewayTransactionId: " + creditCardResponse.GatewayTxnId;
            response = response + "tGatewayResponseCode: " + creditCardResponse.GatewayRspCode;
            response = response + "tGatewayResponseMessage: " + creditCardResponse.GatewayRspMsg;
            response = response + "tResponseCode: " + creditCardResponse.RspCode;
            response = response + "tAuthorizationCode: " + creditCardResponse.AuthCode;
            response = response + "tHPICN: " + creditCardResponse.HPICN;
            this.spanResults.InnerHtml = response;
        }
    }
}

and here is the html file:

<html>
	<head>
		<title>Heritage CC Post</title>

<script type="text/javascript" src="_ScriptHelpers.js"></script>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>

<script type="text/javascript">

</script>
</head>
<body>
	<p>
	Here we are
</p>
<table id="tblParams" border="1" width="90%">
 <tr>
	 <td style="font-weight:bold">ClientNumber</td>
	 <td><input id="ClientNumber" value="4081" /></td>
	 <td style="font-weight:bold">ClientCode</td>
	 <td><input id="ClientCode" value="C" /></td>
	 <td style="font-weight:bold">AccountNumber</td>
	 <td><input id="AccountNumber" value="012345678" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">CardType</td>
	 <td><input id="CardType" value="VISA" /></td>
	 <td style="font-weight:bold">CardNumber</td>
	 <td><input id="CardNumber" value="4012002000060016" /></td>
	 <td style="font-weight:bold">CVV2</td>
	 <td><input id="CVV2" value="123" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">ExpiryMonth</td>
	 <td><input id="ExpiryMonth" value="11" /></td>
	 <td style="font-weight:bold">ExpiryYear</td>
	 <td><input id="ExpiryYear" value="2016" /></td>
	 <td style="font-weight:bold">Amount</td>
	 <td><input id="Amount" value="100.00" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">FirstName</td>
	 <td><input id="FirstName" value="JOHN" /></td>
	 <td style="font-weight:bold">LastName</td>
	 <td><input id="LastName" value="DOE" /></td>
	 <td style="font-weight:bold">Address</td>
	 <td><input id="Address" value="2402 WILWOOD AVENUE" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">City</td>
	 <td><input id="City" value="SHERWOOD" /></td>
	 <td style="font-weight:bold">State</td>
	 <td><input id="State" value="AR" /></td>
	 <td style="font-weight:bold">ZipCode</td>
	 <td><input id="ZipCode" value="72120" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">UserData</td>
	 <td><input id="UserData" value="Unify_UserData" /></td>
	 <td style="font-weight:bold">UserID</td>
	 <td><input id="UserID" value="Unify" /></td>
	 <td style="font-weight:bold">&nbsp;</td>
	 <td>&nbsp;</td>
	 </tr>
</table>
	<br/>
	<input id="btnDoPost" type="button" value="DoPost" onclick="return DoPost();"/>
	<br/>
	<p>Results below:<br/>
	<span id="spanResults">&nbsp;</span>
	</p>

</body>
</html>

and here is the Post.asmx file

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web.Script.Services;
using System.Web.Services;
using System.Xml;

namespace HeritageCompany
{
    [System.ComponentModel.ToolboxItem(false), ScriptService, WebService(Namespace = "http://unify.com/products/contact-centers/Campaign-Director/PS/HeritageCC"), WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    //[ToolboxItem(false), ScriptService, WebService(Namespace = "http://tempuri.org/"), WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Post : WebService
    {
        [WebMethod]
        public CreditCardResponse DoPost(CreditCardRequest creditCardRequest)
        {
            IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
            LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
            LogWriter logWriter = logWriterFactory.Create();
            this.LogMessage(logWriter, "General", "DoPost()", "beginning of function...", System.Diagnostics.TraceEventType.Verbose, 10);
            string sendXml = string.Empty;
            string logXml = string.Empty;
            string g_xml = "<?xml version="1.0" encoding="UTF-8"?><PosRequest><Header><ClientNumber></ClientNumber><ClientCode></ClientCode><AccountNumber></AccountNumber>";
            g_xml += "<UserData></UserData><UserID></UserID></Header><CreditSale><CardData><CardType></CardType><CardNumber></CardNumber><ExpiryMonth></ExpiryMonth><ExpiryYear></ExpiryYear>";
            g_xml += "<CardPresent>N</CardPresent><ReaderPresent>N</ReaderPresent><CVV2></CVV2></CardData><Amount></Amount><CardHolderData><FirstName></FirstName><LastName></LastName>";
            g_xml += "<Address></Address><City></City><State></State><ZipCode></ZipCode></CardHolderData></CreditSale></PosRequest>";
            string sFields = "ClientNumber,ClientCode,AccountNumber,CardType,CardNumber,ExpiryMonth,ExpiryYear,CVV2,Amount,FirstName,LastName,Address,City,State,ZipCode,UserData,UserID";
            string[] aFields = sFields.Split(new char[]
            {
                ','
            });
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(g_xml);
            for (int i = 0; i < aFields.Length; i++)
            {
                xDoc.SelectSingleNode("//" + aFields[i]).InnerXml = (string)creditCardRequest[aFields[i]];
            }
            sendXml = "xml="" + xDoc.OuterXml + """;
            logXml = sendXml.Replace(creditCardRequest["CardNumber"].ToString(), "blahblahblah");
            this.LogMessage(logWriter, "General", "Request", logXml, System.Diagnostics.TraceEventType.Verbose, 20);
            string CCServiceUrl = ConfigurationManager.AppSettings["CCServiceUrl"];
            System.Net.WebRequest request = System.Net.WebRequest.Create(CCServiceUrl);
            request.UseDefaultCredentials = true;
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (System.Net.Security.RemoteCertificateValidationCallback)System.Delegate.Combine(System.Net.ServicePointManager.ServerCertificateValidationCallback, new System.Net.Security.RemoteCertificateValidationCallback(Post.ValidateServerCertificate));
            request.Method = "POST";
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(sendXml);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = (long)byteArray.Length;
            System.IO.Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            System.Net.WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            responseFromServer = responseFromServer.Replace("r", "");
            responseFromServer = responseFromServer.Replace("n", "");
            responseFromServer = responseFromServer.Replace("  ", "");
            this.LogMessage(logWriter, "General", "Response", responseFromServer, System.Diagnostics.TraceEventType.Verbose, 20);
            xDoc.LoadXml(responseFromServer);
            CreditCardResponse creditCardResponse = new CreditCardResponse(xDoc.SelectSingleNode("//GatewayTxnId").InnerXml, xDoc.SelectSingleNode("//GatewayRspCode").InnerXml, xDoc.SelectSingleNode("//GatewayRspMsg").InnerXml, xDoc.SelectSingleNode("//RspCode").InnerXml, xDoc.SelectSingleNode("//AuthCode").InnerXml, xDoc.SelectSingleNode("//HPICN").InnerXml);
            reader.Close();
            dataStream.Close();
            response.Close();
            logWriter.Dispose();
            logWriterFactory.Dispose();
            configurationSource.Dispose();
            return creditCardResponse;
        }
        public static bool ValidateServerCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public void InitializeLogger()
        {
        }
        public void LogMessage(LogWriter logWriter, string categories, string title, string message, System.Diagnostics.TraceEventType traceEventType, int priority)
        {
            string[] a_Categories = categories.Split(new char[]
            {
                ','
            });
            logWriter.Write(new LogEntry
            {
                Title = title,
                Message = message,
                Priority = priority,
                Categories = a_Categories,
                Severity = traceEventType
            });
        }
    }
}

codes above are main ones if you need related codes, I can supply it. Thank you very much for your help

после обновление CU на Exchange 2013 перестали подключаться Outlook 2016
клиенты Outlook 2010, 2013 работают, OWA работает, новые 2016 — нет — постоянно запрашивает пароль (внутри сети и снаружи)
https*testconnectivity.microsoft.com сообщает:

Attempting to send an Autodiscover POST request to potential Autodiscover URLs.
Autodiscover settings weren't obtained when the Autodiscover POST request was sent.

Additional Details

Elapsed Time: 1952 ms.

Test Steps

The Microsoft Connectivity Analyzer is attempting to retrieve an XML Autodiscover response from URL https://autodiscover.mydomain.ru:443/Autodiscover/... for user derba@mydomain.ru.
The Microsoft Connectivity Analyzer failed to obtain an Autodiscover XML response.

Additional Details

An HTTP 500 response was returned from Unknown.
HTTP Response Headers:
request-id: 28560d3f-60a9-4d38-ba3e-9fe5d42aecc8
X-CalculatedBETarget: kvmail.mydomain.local
X-DiagInfo: KVMAIL
X-BEServer: KVMAIL
Cache-Control: private
Set-Cookie: ClientId=9QNDYXGKKVZALFBOSQ; expires=Wed, 25-Jul-2018 08:38:55 GMT; path=/; HttpOnly,X-BackEndCookie=S-1-5-21-1903798712-2405474663-4193718316-2295=u56Lnp2ejJqBz53IzJybxsrSxsfNntLLzsnG0sbJmczSzsyenMecyJqbzp2egYHNz87I0s/H0s3Lq8/HxczHxcrJ; expires=Thu, 24-Aug-2017 08:38:56 GMT; path=/Autodiscover; secure; HttpOnly
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
X-FEServer: KVMAIL
Date: Tue, 25 Jul 2017 08:38:55 GMT
Content-Length: 0
Elapsed Time: 1952 ms.

накатил CU 15 — не помогло … накатил CU 17 — не помогло.

все URL в виртуальных каталогах внешнего адреса mail.mydomain.ru , в DNS идет ссылка на внутренний сервер
mail.mydomain.ru 192.168.0.12
autodiscover.mydomain.ru 12.168.0.12
kvmail.mydomain.local 192.168.0.12

сертификат куплен, в нем прописан mail.mydomain.ru, сертификат весит на службах IIS, SMTP

пересоздавал все виртуальные каталоги 
делал наследование на пользователей домена (расширенные компоненты) 
в IIS на каталоги дал явно права на C:inetpubwwwroot пользователям «прошедшим проверку» на чтение и выполнение

при открытии https*192.168.0.12/Autodiscover/Autodiscover.xml (извне
тоже самое) запрашивает пароль, после ввода показывает:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
600Недопустимый запрос

переставлял IIS — не помогло.

[PS] C:>get-autodiscovervirtualdirectory | fl *path*
Выполняется создание нового сеанса для неявного удаленного взаимодействия команды "Get-AutodiscoverVirtualDirectory"...

MetabasePath : IIS://kvmail.mydomain.local/W3SVC/1/ROOT/Autodiscover
Path : C:Program FilesMicrosoftExchange ServerV15FrontEndHttpProxyAutodiscover

для пользователей «Прошедшие проверку» явно указал до папки C:Program FilesMicrosoftExchange ServerV15FrontEndHttpProxyAutodiscover права на чтение

[PS] C:>iisreset /noforce

Попытка остановки...
Службы Интернета успешно остановлены
Попытка запуска...
Службы Интернета успешно перезапущены
[PS] C:>Test-WebServicesConnectivity
Выполняется создание нового сеанса для неявного удаленного взаимодействия команды "Test-WebServicesConnectivity"...

Source ServiceEndpoint Scenario Result Latency
(MS)
------ --------------- -------- ------ -------
KVMAIL.domain.local autodiscover.mydomain.ru Автообнаружение: поставщик ... Failure 551
KVMAIL.domain.local EWS: GetFolder Skipped 0

[PS] C:>
[PS] C:>Test-WebServicesConnectivity | fl

RunspaceId : 6cf74bba-9812-4863-8641-88f1f3eeb753
Source : KVMAIL.domain.local
ServiceEndpoint : autodiscover.mydomain.ru
Scenario : AutoDiscoverSoapProvider
ScenarioDescription : Автообнаружение: поставщик SOAP
Result : Failure
Latency : 50
Error : System.Net.WebException: Удаленный сервер возвратил ошибку: (500) Внутренняя ошибка сервера.
в System.Net.HttpWebRequest.GetResponse()
в Microsoft.Exchange.Management.SystemConfigurationTasks.ServiceValidatorBase.InternalInvoke()
в Microsoft.Exchange.Management.SystemConfigurationTasks.ServiceValidatorBase.Invoke()
Verbose : [2017-07-25 22:06:20Z] Подключение Автообнаружение к "https://autodiscover.mydomain.ru/autodiscover/auto...".
[2017-07-25 22:06:20Z] Тестовая учетная запись: extest_91809daefd5e4@domain.local Пароль: ******
[2017-07-25 22:06:20Z] Запрос Автообнаружение:
User-Agent: KVMAIL/Test-WebServicesConnectivity/extest_91809daefd5e4@domain.local
Content-Type: text/xml; charset=utf-8
Authorization: Negotiate TlRMTVNTUAADAAAAGAAYAKoAAABkAWQBwgAAAAAAAABYAAAARABEAFgAAAAOAA4AnAAAABAAEAAmAgAAFYKI4gYDgCUAAAAP2jc/Z1olP4tXSSAeEc
AF8AOQAxADgAMAA5AGQAYQBlAGYAZAA1AGUANABAAG0AYQBnAGEAZABhAG4ALgBsAG8AYwBhAGwASwBWAFAATQBBAEkATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzGxPzJfeumcZ
ABIAiY/kgXTAT9/szZqaD2kAAAAAAIADgBNAEEARwBBAEQAQQBOAAEADgBLAFYAUABNAEEASQBMAAQAGgBtAGEAZwBhAGQAYQBuAC4AbABvAGMAYQBsAAMAKgBrAHYAcABtAGEAaQBs
EAbgAuAGwAbwBjAGEAbAAFABoAbQBhAGcAYQBkAGEAbgAuAGwAbwBjAGEAbAAHAAgASAImP5IF0wEGAAQAAgAAAAgAMAAwAAAAAAAAAAAAAAAAQAAAZB7M3pgHJN9JMYimsUzCsbO/A
KABAAx8wbQsBX7MrEx9zBcspCtAkAPgBIAFQAVABQAC8AYQB1AHQAbwBkAGkAcwBjAG8AdgBlAHIALgBtAGEAZwBhAGQAYQBuAGsAdgBwAC4AcgB1AAAAAAAAAAAAAAAAAEPe+B6G5X
Host: autodiscover.mydomain.ru
Cookie: ClientId=BEQIIQTUOFXWHNXSLG
Content-Length: 1149
Expect: 100-continue
[2017-07-25 22:06:20Z] Запрос Автообнаружение:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
Exchange2010schemas.microsoft.com/exchange/2010/Autodiscover/A...

[2017-07-25 22:06:20Z] Ответ Автообнаружение:
request-id: d3514bb0-2f8f-4a05-a0ab-b08652c42180
X-CalculatedBETarget: KVMAIL.domain.local
X-DiagInfo: KVMAIL
X-BEServer: KVMAIL
Persistent-Auth: true
X-FEServer: KVMAIL
Content-Length: 0
Cache-Control: private
Date: Tue, 25 Jul 2017 22:06:19 GMT
Set-Cookie: X-BackEndCookie=S-1-5-21-1903798712-2405474663-4193718316-2291=u56Lnp2ejJqBzJ6byMyZxszSxpvMyNLLzZzO0seax53Sx5qbnp3Pys6az8zMgYHN
/Jxc3P; expires=Thu, 24-Aug-2017 22:06:20 GMT; path=/autodiscover; secure; HttpOnly
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
[2017-07-25 22:06:20Z] Ответ Автообнаружение:
System.Net.WebException: Удаленный сервер возвратил ошибку: (500) Внутренняя ошибка сервера.
в System.Net.HttpWebRequest.GetResponse()
в Microsoft.Exchange.Management.SystemConfigurationTasks.ServiceValidatorBase.InternalInvoke()
в Microsoft.Exchange.Management.SystemConfigurationTasks.ServiceValidatorBase.Invoke()
MonitoringEventId : 6051

RunspaceId : 6cf74bba-9812-4863-8641-88f1f3eeb753
Source : KVMAIL.domain.local
ServiceEndpoint :
Scenario : EwsGetFolder
ScenarioDescription : EWS: GetFolder
Result : Skipped
Latency : 0
Error : Пропущено тестирование веб-служб Exchange из-за ошибки на шаге автообнаружения.
Verbose :
MonitoringEventId : 5053

Problem

Error message appear when you try to browse your content in Office document

Symptom

Error mesage :
System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
at Cognos.Office.Framework.DataSource.Cognos8.HttpConnection.Send(String sSOAPRequestBody, String sAction, Boolean cacheResult)
at Cognos.Office.Framework.DataSource.Cognos8.HttpConnection.Send(ISOAPRequest request)
at CognosOfficeConnection.Datasource.ReportStore.PortalTree_DoWork(RequestInfo req)
at Cognos.Office.Framework.Threading.ThreadPool.doWork(RequestInfo requestInfo)
at Cognos.Office.Framework.Threading.AsyncCall.AsyncItem`3.Run()
at Cognos.Office.Framework.Threading.AsyncCall.CallMethod()

Cause

wrong settings in IIS 7.x

Resolving The Problem

Open IIS7.x Administartion tool by running “Start>Run>inetmgr.exe”,
selecting your website/application/virtual directory in the left-hand tree view,
clicking on the “Error Pages” icon,
clicking “Edit Feature Settings” action,
and then selecting “Detailed Errors”.
Stop and start IIS

[{«Product»:{«code»:»SSEP7J»,»label»:»Cognos Business Intelligence»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud u0026 Data Platform»},»Component»:»Cognos for Microsoft Office»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»10.1.1;10.1″,»Edition»:»»,»Line of Business»:{«code»:»»,»label»:»»}}]

logo424

35 / 25 / 13

Регистрация: 12.02.2011

Сообщений: 178

Записей в блоге: 1

1

18.11.2013, 23:24. Показов 7045. Ответов 4

Метки нет (Все метки)


Доброго времени, у меня проблема с запросом, а точней с кодом ответа..
200 — нормальный статус
500 — ошибка

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  public string post(string uri, string req)
    {
 
            string s = req;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.UserAgent = "Opera/9.80";
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] bytes = Encoding.ASCII.GetBytes(s);
            request.ContentLength = bytes.Length;
            request.GetRequestStream().Write(bytes, 0, bytes.Length);
            request.GetRequestStream().Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            statusCode = (int)response.StatusCode;
            return new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
 
      }

как только получаю 500
Высвечивается «webexception не обработано…»
Удаленный сервер возвратил ошибку: (500) Внутренняя ошибка сервера.
и подсвечивает эту часть
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

=====
Как решить можно?

Добавлено через 21 час 8 минут
эм есть кто знает?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Master of Orion

Эксперт .NET

6094 / 4950 / 905

Регистрация: 10.07.2011

Сообщений: 14,522

Записей в блоге: 5

19.11.2013, 10:34

2

logo424, берете программу fidler2 версии 4 и смотрите, что по факту отправляется
И не пишите все в одну строчку, у вас из-за этого куча временных объектов, не удаляемых сборщиком, висит

0

35 / 25 / 13

Регистрация: 12.02.2011

Сообщений: 178

Записей в блоге: 1

19.11.2013, 11:58

 [ТС]

3

Цитата
Сообщение от Psilon
Посмотреть сообщение

logo424, берете программу fidler2 версии 4 и смотрите, что по факту отправляется
И не пишите все в одну строчку, у вас из-за этого куча временных объектов, не удаляемых сборщиком, висит

у меня другой сниффер…
Я уже решил проблему

0

Master of Orion

Эксперт .NET

6094 / 4950 / 905

Регистрация: 10.07.2011

Сообщений: 14,522

Записей в блоге: 5

19.11.2013, 11:59

4

logo424, ну опишите тогда…

0

35 / 25 / 13

Регистрация: 12.02.2011

Сообщений: 178

Записей в блоге: 1

19.11.2013, 22:59

 [ТС]

5

Цитата
Сообщение от Psilon
Посмотреть сообщение

logo424, ну опишите тогда…

повторяю запрос если вылетела ошибка, try catch
у меня много запросов 1к+ и массив данных, так что мое повторение продолжает процесс а не обрывает

0

In this article I will explain how to solve the following error (exception) occurring inside the GetResponse method of HttpWebRequest class in C# and VB.Net.

An exception of type ‘System.Net.WebException’ occurred in System.dll but was not handled in user code. Additional information: The remote server returned an error: (500) Internal Server Error.

Exception

In following code snippet, the response is being received using the GetResponse method of HttpWebRequest class.

using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())

{

    using (Stream stream = httpResponse.GetResponseStream())

    {

        string json = (new StreamReader(stream)).ReadToEnd();

    }

}

But it raises the following exception:-

An exception of type ‘System.Net.WebException’ occurred in System.dll but was not handled in user code. Additional information: The remote server returned an error: (500) Internal Server Error.

HttpWebRequest GetResponse: The remote server returned an error: (500) Internal Server Error

Reason

This exception could be occurring due to any internal error related to database, runtime error, etc. But problem is the above exception does not give any information why the exception is occurring.

Solution

Though this is not a solution, it will help us find the real cause of the exception.

The code snippet is now wrapped into a Try-Catch block and the WebException is caught in the Catch block.

The exception details are extracted from the WebException object using StreamReader class.

try

{

    using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())

    {

        using (Stream stream = httpResponse.GetResponseStream())

        {

            string json = (new StreamReader(stream)).ReadToEnd();

            gvCustomers.DataSource = (new JavaScriptSerializer()).Deserialize<List<Customer>>(json);

            gvCustomers.DataBind();

        }

    }

}

catch (WebException ex)

{

    string message = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

}

Now when the code is again executed, the details of the exception occurring are now available in the message variable.

HttpWebRequest GetResponse: The remote server returned an error: (500) Internal Server Error

Download Free Word/PDF/Excel API


Comments


No comments have been added to this article.

User-621232634 posted

Hello guys,

  I have the following error and I have no idea how to fix it. I tried but I couldn’t figure out the solution yet. Please if anyone can offer help, I would appreciate that.  

Server Error in '/' Application.

The remote server returned an error: (500) Internal Server Error. 
  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 remote server returned an error: (500) Internal Server Error.

Source Error: 



Line 105:            PostSoapClient oClient = new PostSoapClient();
Line 106:            oClient.Open();
Line 107:            HeritageCompany.wsPost.CreditCardResponse creditCardResponse = oClient.DoPost(creditCardRequest);
Line 108:            string response = "GatewayTransactionId: " + creditCardResponse.GatewayTxnId;
Line 109:            response = response + "tGatewayResponseCode: " + creditCardResponse.GatewayRspCode;
  

 Source File:  C:Usersmontadardocumentsvisual studio 2015ProjectsHeritageCompanyHeritageCompanyTest.aspx.cs    Line:  107 

Stack Trace: 



[WebException: The remote server returned an error: (500) Internal Server Error.]
   System.Net.HttpWebRequest.GetResponse() +1390
   System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +55

[ProtocolException: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '<!DOCTYPE html>
<html>
    <head>
        <title>Parser Error</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; ov'.]
   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +153
   System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336
   HeritageCompany.wsPost.PostSoap.DoPost(DoPostRequest request) +0
   HeritageCompany.wsPost.PostSoapClient.HeritageCompany.wsPost.PostSoap.DoPost(DoPostRequest request) +73
   HeritageCompany.wsPost.PostSoapClient.DoPost(CreditCardRequest creditCardRequest) +123
   HeritageCompany.Test.btnPost_Click(Object sender, EventArgs e) in C:Usersmontadardocumentsvisual studio 2015ProjectsHeritageCompanyHeritageCompanyTest.aspx.cs:107
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696754
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

 

Here is the code in C#: It throw an error and when it hits this line : HeritageCompany.wsPost.CreditCardResponse creditCardResponse = oClient.DoPost(creditCardRequest);

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.ServiceModel.Channels;
using HeritageCompany.wsPost;
namespace HeritageCompany
{
    public class Test : Page
    {
        protected HtmlForm form1;

        protected TextBox tbClientNumber;

        protected TextBox tbClientCode;

        protected TextBox tbAccountNumber;

        protected TextBox tbCardType;

        protected TextBox tbCardNumber;

        protected TextBox tbCVV2;

        protected TextBox tbExpiryMonth;

        protected TextBox tbExpiryYear;

        protected TextBox tbAmount;

        protected TextBox tbFirstName;

        protected TextBox tbLastName;

        protected TextBox tbAddress;

        protected TextBox tbCity;

        protected TextBox tbState;

        protected TextBox tbZipCode;

        protected TextBox tbUserData;

        protected TextBox tbUserID;

        protected Button btnPost;

        protected HtmlGenericControl spanResults;

        public IConfigurationSource configurationSource = null;

        public LogWriterFactory logWriterFactory = null;

        public LogWriter logWriter = null;

        protected void Page_Load(object sender, System.EventArgs e)
        {
        }

        public void InitializeLogger()
        {
            this.configurationSource = ConfigurationSourceFactory.Create();
            this.logWriterFactory = new LogWriterFactory(this.configurationSource);
            this.logWriter = this.logWriterFactory.Create();
        }

        public void LogMessage(string categories, string message, System.Diagnostics.TraceEventType traceEventType, int priority)
        {
            string[] a_Categories = categories.Split(new char[]
            {
                ','
            });
            LogEntry logEntry = new LogEntry();
            logEntry.Message = message;
            logEntry.Priority = priority;
            logEntry.Categories = a_Categories;
            logEntry.Severity = traceEventType;
            this.logWriter.Write(logEntry);
        }

        protected void btnPost_Click(object sender, System.EventArgs e)
        {
            HeritageCompany.wsPost.CreditCardRequest creditCardRequest = new HeritageCompany.wsPost.CreditCardRequest();
            creditCardRequest.ClientNumber = this.tbClientNumber.Text;
            creditCardRequest.ClientCode = this.tbClientCode.Text;
            creditCardRequest.AccountNumber = this.tbAccountNumber.Text;
            creditCardRequest.CardType = this.tbCardType.Text;
            creditCardRequest.CardNumber = this.tbCardNumber.Text;
            creditCardRequest.ExpiryMonth = this.tbExpiryMonth.Text;
            creditCardRequest.ExpiryYear = this.tbExpiryYear.Text;
            creditCardRequest.CVV2 = this.tbCVV2.Text;
            creditCardRequest.Amount = this.tbAmount.Text;
            creditCardRequest.FirstName = this.tbFirstName.Text;
            creditCardRequest.LastName = this.tbLastName.Text;
            creditCardRequest.Address = this.tbAddress.Text;
            creditCardRequest.City = this.tbCity.Text;
            creditCardRequest.State = this.tbState.Text;
            creditCardRequest.ZipCode = this.tbZipCode.Text;
            creditCardRequest.UserData = this.tbUserData.Text;
            creditCardRequest.UserID = this.tbUserID.Text;
            PostSoapClient oClient = new PostSoapClient();
            oClient.Open();
            HeritageCompany.wsPost.CreditCardResponse creditCardResponse = oClient.DoPost(creditCardRequest);
            string response = "GatewayTransactionId: " + creditCardResponse.GatewayTxnId;
            response = response + "tGatewayResponseCode: " + creditCardResponse.GatewayRspCode;
            response = response + "tGatewayResponseMessage: " + creditCardResponse.GatewayRspMsg;
            response = response + "tResponseCode: " + creditCardResponse.RspCode;
            response = response + "tAuthorizationCode: " + creditCardResponse.AuthCode;
            response = response + "tHPICN: " + creditCardResponse.HPICN;
            this.spanResults.InnerHtml = response;
        }
    }
}

and here is the html file:

<html>
	<head>
		<title>Heritage CC Post</title>

<script type="text/javascript" src="_ScriptHelpers.js"></script>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>

<script type="text/javascript">

</script>
</head>
<body>
	<p>
	Here we are
</p>
<table id="tblParams" border="1" width="90%">
 <tr>
	 <td style="font-weight:bold">ClientNumber</td>
	 <td><input id="ClientNumber" value="4081" /></td>
	 <td style="font-weight:bold">ClientCode</td>
	 <td><input id="ClientCode" value="C" /></td>
	 <td style="font-weight:bold">AccountNumber</td>
	 <td><input id="AccountNumber" value="012345678" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">CardType</td>
	 <td><input id="CardType" value="VISA" /></td>
	 <td style="font-weight:bold">CardNumber</td>
	 <td><input id="CardNumber" value="4012002000060016" /></td>
	 <td style="font-weight:bold">CVV2</td>
	 <td><input id="CVV2" value="123" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">ExpiryMonth</td>
	 <td><input id="ExpiryMonth" value="11" /></td>
	 <td style="font-weight:bold">ExpiryYear</td>
	 <td><input id="ExpiryYear" value="2016" /></td>
	 <td style="font-weight:bold">Amount</td>
	 <td><input id="Amount" value="100.00" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">FirstName</td>
	 <td><input id="FirstName" value="JOHN" /></td>
	 <td style="font-weight:bold">LastName</td>
	 <td><input id="LastName" value="DOE" /></td>
	 <td style="font-weight:bold">Address</td>
	 <td><input id="Address" value="2402 WILWOOD AVENUE" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">City</td>
	 <td><input id="City" value="SHERWOOD" /></td>
	 <td style="font-weight:bold">State</td>
	 <td><input id="State" value="AR" /></td>
	 <td style="font-weight:bold">ZipCode</td>
	 <td><input id="ZipCode" value="72120" /></td>
	 </tr>
	 <tr>
	 <td style="font-weight:bold">UserData</td>
	 <td><input id="UserData" value="Unify_UserData" /></td>
	 <td style="font-weight:bold">UserID</td>
	 <td><input id="UserID" value="Unify" /></td>
	 <td style="font-weight:bold">&nbsp;</td>
	 <td>&nbsp;</td>
	 </tr>
</table>
	<br/>
	<input id="btnDoPost" type="button" value="DoPost" onclick="return DoPost();"/>
	<br/>
	<p>Results below:<br/>
	<span id="spanResults">&nbsp;</span>
	</p>

</body>
</html>

and here is the Post.asmx file

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web.Script.Services;
using System.Web.Services;
using System.Xml;

namespace HeritageCompany
{
    [System.ComponentModel.ToolboxItem(false), ScriptService, WebService(Namespace = "http://unify.com/products/contact-centers/Campaign-Director/PS/HeritageCC"), WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    //[ToolboxItem(false), ScriptService, WebService(Namespace = "http://tempuri.org/"), WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Post : WebService
    {
        [WebMethod]
        public CreditCardResponse DoPost(CreditCardRequest creditCardRequest)
        {
            IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
            LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
            LogWriter logWriter = logWriterFactory.Create();
            this.LogMessage(logWriter, "General", "DoPost()", "beginning of function...", System.Diagnostics.TraceEventType.Verbose, 10);
            string sendXml = string.Empty;
            string logXml = string.Empty;
            string g_xml = "<?xml version="1.0" encoding="UTF-8"?><PosRequest><Header><ClientNumber></ClientNumber><ClientCode></ClientCode><AccountNumber></AccountNumber>";
            g_xml += "<UserData></UserData><UserID></UserID></Header><CreditSale><CardData><CardType></CardType><CardNumber></CardNumber><ExpiryMonth></ExpiryMonth><ExpiryYear></ExpiryYear>";
            g_xml += "<CardPresent>N</CardPresent><ReaderPresent>N</ReaderPresent><CVV2></CVV2></CardData><Amount></Amount><CardHolderData><FirstName></FirstName><LastName></LastName>";
            g_xml += "<Address></Address><City></City><State></State><ZipCode></ZipCode></CardHolderData></CreditSale></PosRequest>";
            string sFields = "ClientNumber,ClientCode,AccountNumber,CardType,CardNumber,ExpiryMonth,ExpiryYear,CVV2,Amount,FirstName,LastName,Address,City,State,ZipCode,UserData,UserID";
            string[] aFields = sFields.Split(new char[]
            {
                ','
            });
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(g_xml);
            for (int i = 0; i < aFields.Length; i++)
            {
                xDoc.SelectSingleNode("//" + aFields[i]).InnerXml = (string)creditCardRequest[aFields[i]];
            }
            sendXml = "xml="" + xDoc.OuterXml + """;
            logXml = sendXml.Replace(creditCardRequest["CardNumber"].ToString(), "blahblahblah");
            this.LogMessage(logWriter, "General", "Request", logXml, System.Diagnostics.TraceEventType.Verbose, 20);
            string CCServiceUrl = ConfigurationManager.AppSettings["CCServiceUrl"];
            System.Net.WebRequest request = System.Net.WebRequest.Create(CCServiceUrl);
            request.UseDefaultCredentials = true;
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (System.Net.Security.RemoteCertificateValidationCallback)System.Delegate.Combine(System.Net.ServicePointManager.ServerCertificateValidationCallback, new System.Net.Security.RemoteCertificateValidationCallback(Post.ValidateServerCertificate));
            request.Method = "POST";
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(sendXml);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = (long)byteArray.Length;
            System.IO.Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            System.Net.WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            responseFromServer = responseFromServer.Replace("r", "");
            responseFromServer = responseFromServer.Replace("n", "");
            responseFromServer = responseFromServer.Replace("  ", "");
            this.LogMessage(logWriter, "General", "Response", responseFromServer, System.Diagnostics.TraceEventType.Verbose, 20);
            xDoc.LoadXml(responseFromServer);
            CreditCardResponse creditCardResponse = new CreditCardResponse(xDoc.SelectSingleNode("//GatewayTxnId").InnerXml, xDoc.SelectSingleNode("//GatewayRspCode").InnerXml, xDoc.SelectSingleNode("//GatewayRspMsg").InnerXml, xDoc.SelectSingleNode("//RspCode").InnerXml, xDoc.SelectSingleNode("//AuthCode").InnerXml, xDoc.SelectSingleNode("//HPICN").InnerXml);
            reader.Close();
            dataStream.Close();
            response.Close();
            logWriter.Dispose();
            logWriterFactory.Dispose();
            configurationSource.Dispose();
            return creditCardResponse;
        }
        public static bool ValidateServerCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public void InitializeLogger()
        {
        }
        public void LogMessage(LogWriter logWriter, string categories, string title, string message, System.Diagnostics.TraceEventType traceEventType, int priority)
        {
            string[] a_Categories = categories.Split(new char[]
            {
                ','
            });
            logWriter.Write(new LogEntry
            {
                Title = title,
                Message = message,
                Priority = priority,
                Categories = a_Categories,
                Severity = traceEventType
            });
        }
    }
}

codes above are main ones if you need related codes, I can supply it. Thank you very much for your help

Никак. На то это и внутренняя ошибка, что клиенту ничего про нее знать не нужно. В браузере вы можете что-то видеть только если сервер запущен с тестовой конфигурацией (когда в случае ошибки отображает страницу со стектрейсом).

UPD

нужное вам поведение можно получить как-то так:

[ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public Task ChangeStatus()
        {
            throw new Exception("My test exception");
        }
    }
public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter
{
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                context.Result = new ObjectResult(new
                {
                    ErrorText = context.Exception.Message,
                    Stacktrace = context.Exception.StackTrace
                })
                { StatusCode = (int)HttpStatusCode.BadRequest };

                context.Exception = null;

                return;
         }
}

тогда дергнув контроллера вы обратно получите 400ую ошибку с контентом

{
«errorText»: «My test exception»,
«stacktrace»: «stacktrace was here»
}

UPD2:
ну и насколько я помню (а я могу быть не прав, но не могу перепроверить сейчас) — HttpWebRequest будет кидать ексепшн для всех не 200 хттп статусов. Потому возможно стектрейс прийдется доставать не очень красиво

WebRequest request = ...;
try
{
  using var response = request.GetResponse();
  ...
}
catch (WebException e)
{
  using var webResponse = (HttpWebResponse)e.Response;
  var code = webResponse.StatusCode;
  var body = ...;

  //...

}

или использовть HttpClient, который ексепшн кидает только если попросить

I have a heavy traffic aspx page calling a web service upon every user`s request as follows.

string uri = "Path.asmx";
string soap = "soap xml string";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Add("SOAPAction", ""http://xxxxxx"");
request.ContentType = "text/xml;charset="utf-8"";
request.Accept = "text/xml";
request.Method = "POST";

using (Stream stm = request.GetRequestStream())
{
    using (StreamWriter stmw = new StreamWriter(stm))
    {
        stmw.Write(soap);
    }
}
WebResponse response = request.GetResponse();
response.close();

Everything is working fine but sometimes I am getting the following error.

The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponse()

Does anybody have any idea about this error or can anybody tell me if I am doing wrong.

Luke Girvin's user avatar

Luke Girvin

13.2k9 gold badges63 silver badges84 bronze badges

asked Nov 4, 2010 at 16:36

Krishna's user avatar

1

For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, HttpPost, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:

catch (WebException webex)
{
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
}

answered Feb 19, 2014 at 13:13

Mohammad Sepahvand's user avatar

5

From that error, I would say that your code is fine, at least the part that calls the webservice. The error seems to be in the actual web service.

To get the error from the web server, add a try catch and catch a WebException. A WebException has a property called Response which is a HttpResponse. you can then log anything that is returned, and upload you code. Check back later in the logs and see what is actually being returned.

Ashkan Mobayen Khiabani's user avatar

answered Nov 4, 2010 at 17:25

FallenAvatar's user avatar

FallenAvatarFallenAvatar

4,0791 gold badge21 silver badges24 bronze badges

Finally I get rid of internal server error message with the following code. Not sure if there is another way to achieve it.


string uri = "Path.asmx";
string soap = "soap xml string";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Add("SOAPAction", ""http://xxxxxx"");
request.ContentType = "text/xml;charset="utf-8"";
request.Accept = "text/xml";
request.Method = "POST";

using (Stream stm = request.GetRequestStream())
{
    using (StreamWriter stmw = new StreamWriter(stm))
    {
        stmw.Write(soap);
    }
}

using (WebResponse webResponse = request.GetResponse())
{
}

answered Nov 8, 2010 at 14:26

Krishna's user avatar

KrishnaKrishna

1,9365 gold badges22 silver badges30 bronze badges

1

Have you tried to specify UserAgent for your request? For example:

request.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";

answered Aug 1, 2013 at 9:02

Roman Gudkov's user avatar

Roman GudkovRoman Gudkov

3,4732 gold badges20 silver badges20 bronze badges

1

looking at your error message first of all I would suggest you to recompile your whole application, make sure all the required dlls are there in bin folder when you recompile it.

answered Aug 18, 2016 at 6:43

Santhosh Legent's user avatar

In my case my request object inherited from base object. Without knowingly I added a property with int? in my request object and my base object also has same property ( same name ) with int datatype. I noticed this and deleted the property which I added in request object and after that it worked fine.

answered Nov 11, 2016 at 17:50

Ziggler's user avatar

ZigglerZiggler

3,3113 gold badges40 silver badges61 bronze badges

For me the error was misleading. I discovered the true error by testing the errant web service with SoapUI.

answered Mar 28, 2017 at 14:05

Graham Laight's user avatar

Graham LaightGraham Laight

4,6703 gold badges29 silver badges28 bronze badges

2

In my case I just remove the SoapAction instruction from the HttpWebRequest object. So, I don’t define .Headers.Add("SOAPAction","someurl") in HttpWebRequest definitions and my code works fine.

ResultXML is an XDocument.
ResultString is a string.

try
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
    //req.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
    req.ProtocolVersion = HttpVersion.Version11;
    req.ContentType = "text/xml;charset="utf-8"";
    req.Accept = "text/xml";
    req.KeepAlive = true;
    req.Method = "POST";        

    using (Stream stm = req.GetRequestStream())
    {
        using (StreamWriter stmw = new StreamWriter(stm))
            stmw.Write(soapStr);
    }
    using (StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream()))
    {
        string result = responseReader.ReadToEnd();
        ResultXML = XDocument.Parse(result);
        ResultString = result;      
    }
}

Paul Roub's user avatar

Paul Roub

36.3k27 gold badges83 silver badges93 bronze badges

answered Aug 19, 2017 at 17:34

Elkin Yecid Quiroz Morales's user avatar

Понравилась статья? Поделить с друзьями:
  • Tabletop simulator ошибка при запуске
  • Tabletop simulator ошибка при загрузке текстур
  • Tabletop simulator ошибка unity
  • Table has no index order set ошибка foxpro
  • T790 ошибка картриджа