I am working on a program that automatically queries a website every 5 seconds. It has been working fine for the last few days, but today when I simply restarted it, it keeps throwing System.ObjectDisposedException on the line marked underneath. I should mention that accessing this URL via a browser on the same machine works fine.
Code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.bitstamp.net/api/ticker/");
request.Method = "GET";
try
{
// ObjectDisposedException thrown here
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string resultString = reader.ReadToEnd();
return resultString;
}
}
}
catch (WebException ex)
{
// Handle it
}
Stack Trace:
System.ObjectDisposedException occurred
_HResult=-2146232798
_message=Cannot access a disposed object.
HResult=-2146232798
IsTransient=false
Message=Cannot access a disposed object.
Object name: 'SslStream'.
Source=System
ObjectName=SslStream
StackTrace:
at System.Net.Security.SslState.ValidateCreateContext(Boolean isServer, String targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, Boolean remoteCertRequired, Boolean checkCertRevocationStatus, Boolean checkCertName)
InnerException:
Is there something I am doing wrong? I do not even access the response stream before the using, how can it be disposed?
EDIT: Added url and stack trace
Simplifying things a bit and just doing a:
WebRequest.Create("https://www.bitstamp.net/api/ticker/").GetResponse();
I'm getting WebException "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF", which apparently is indicative of a problem at the server end, and one (perhaps the only) way round it is to add the following to your config file:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
Worked for me anyway.
Related
I used ASP.NET to write a web page that accesses other websites to log in to the API, and it was successfully placed on my server, but when it was placed on the school's server to receive the token from the post, the following error was reported:
Server Error in '/classMeeting' Application. A connection attempt failed because the connecting party did not properly reply after a period of time or the connected host became unresponsive. 112.65.235.59:443
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.Sockets.SocketException:
A connection attempt failed because the connected party did not properly reply after a period of time or the connected host became unresponsive. 112.65.235.59:443
Source Error:
An unhandled exception was generated during the execution of the current webrequest. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +309
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +633
System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) +708
System.Net.HttpWebRequest.GetRequestStream() +21
classMeeting.index.GetAccess_token(String code, String client_id, String redirect_uri, String client_secret) in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:130 classMeeting.index.readyLogin() in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:32
classMeeting.index.Page_Load(Object sender, EventArgs e) in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:25
System.Web.UI.Control.OnLoad(EventArgs e) +109
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3321
My source code is:
public static string GetAccess_token(string code, string client_id, string redirect_uri, string client_secret)
{
var url = "https://openapi.yiban.cn/oauth/access_token";
byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", client_id, client_secret, code, redirect_uri));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "Post";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
ServicePointManager.DefaultConnectionLimit = 50;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);
return php.ReadToEnd();
}
How should we do to fix this error?
If you get any error code like 10036 for a socket connection error then you can find the related error section from this link
Check the parameters you use for connection like hostname and port, and also make sure your firewall doesn't drop packages or block your connection.
The code you provided is correct, there are several reasons for this phenomenon:
Check whether the status of the server is abnormal. For example, there may be a state of not starting or being paralyzed.
Whether the status of your destination URL is normal. Whether there is an unreachable state.
Whether your server can access your target website. Due to the server's need for a secure environment, there are usually some URLs that cannot be accessed by the server. At this point you need to change your server port. If it still doesn't work, try sending and receiving web requests to hosts that it can access successfully.
In our MVC 5 site we have a VerifyEmail method that contacts a service to check that an email exists. We do the basic preliminary checks, to make sure it looks like a valid email, etc, then we pass it to the service.
We're using a WebClient.DownloadString() function. When we navigate to the appropriate View and trigger the method, we get these errors:
When debugging:
<h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
When we're not debugging, we get this:
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:63595
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
If I call the method (VerifyEmailOrgEmailVerificationClient.VerifyEmail) from LinqPad it works!!!
I get this:
MX record about emailserver.com exists.<br/>
Connection succeeded to emailserver-com.mail.protection.outlook.com SMTP.<br/>
220 SN1NAM01FT022.mail.protection.outlook.com Microsoft ESMTP MAIL Service ready at Mon, 29 Feb 2016 21:08:50 +0000<br/>
> HELO verify-email.org<br/>
250 SN1NAM01FT022.mail.protection.outlook.com Hello [verify-email.org]<br/>
> MAIL FROM: <check#verify-email.org><br/>
=250 2.1.0 Sender OK<br/>
> RCPT TO: <redacted#emailserver.com><br/>
=250 2.1.5 Recipient OK<br/>
That's what we should get. So, the code works from LinqPad, but not when we call it as a website. We put a test method together and get the same results. With our test, we're just trying to get a response from WebClient.DownloadString(). Even like that we get an error.
Here's our test method:
using System;
using System.IO;
using System.Net;
using System.Web.Mvc;
using PublicationSystem.ViewModels;
namespace TestWebClient.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var newModel = new TestViewModel();
using (var webClient = new WebClient())
{
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.Headers["Content-Type"] = "application/json;charset=UTF-8";
var requestUrl = string.Empty;// GetRequestUrl(email);
try
{
requestUrl =
"http://api.verify-email.org/api.php?usr=igiglobal&pwd=emailsareweak&check=mkenyon#mkptechnologies.com";
newModel.ResponseString = webClient.DownloadString(requestUrl);
}
catch (WebException exception)
{
string responseText;
if (exception.Response != null)
{
using (var reader = new StreamReader(exception.Response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
}
newModel.ResponseString = responseText;
}
else
{
newModel.ResponseString = exception.ToString();
}
}
catch (Exception exception)
{
newModel.ResponseString = exception.ToString();
}
}
return View(newModel);
}
Our AppPool is set for .Net 4.0. The app compiles for .Net 4.5. We're using MVC 5.
Any idea why our method, specifically the WebClient.DownloadString() fails while we're running the site, but works if we call the code from LinqPad?
UPDATE: I created a new MVC project with Visual Studio 2013, just like this project. In the new test project, I pasted the same code, and have tried to get the references to match as exactly as possible. My code works in the test project. So something with the way my project is set up is blocking WebClient.DownloadString(). Using Fiddler, it looks like it doesn't even send the request out.
Is there a setting that could block WebClient.DownloadString() while testing an MVC site?
UPDATE 2: In the web.config I found this. Could this be it?
<system.net>
<defaultProxy>
<proxy proxyaddress="http://localhost:63595/" />
</defaultProxy>
</system.net>
In the web.config I found this. Commenting it out let WebClient.DownloadString() work again. Hope this helps somebody. I'll have to do more research on this.
<system.net>
<defaultProxy>
<proxy proxyaddress="http://localhost:63595/" />
</defaultProxy>
</system.net>
As the title says I am trying to run a Windows Phone App which is supposed to communicate with a Restful API(running on localhost). My server is actually getting my Http requests but Visual Studio keeps throwing this error:
"The remote server returned an error: NotFound."
private void connect_tap(object sender, System.Windows.Input.GestureEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.BeginGetResponse(GetResponseCallback, request);
}
void GetResponseCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
WebResponse response = request.EndGetResponse(result);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string read = streamRead.ReadToEnd();
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(read);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
});
streamResponse.Close();
streamRead.Close();
response.Close();
}
}
This is the full error:
{System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at IonisSphere.Connect.GetResponseCallback(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass1d.b__1b(Object state2)}
The Web Exception occurs at the EndGetResponse() call. I removed the try/catch around to see the error but when it's there it always goes in the catch section and nothing happens.
I don't understand what is it not finding since my server gets my requests ...
It works fine with Postman by the way. I also tried with a POST method but got exactly the same result.
I'm stuck with this since a few days and I couldn't find anyhing helpful on the internet. I am quite new on Windows Phone and I know this is propably a stupid mistake but thanks in advance for the ones who will try to teach me =)
Our console applications are making hundreds of WebRequests to Facebook every minute (with using multiple apps and hundreds of access tokens). Now, they started to fail with the exception message in the title ("The request was aborted: The request was canceled"). We searched for hours on the internet, and tried out every possible solution, but nothing helped.
These didn't help:
webRequest.Timeout = 20000; //A request that didn't get respond within 20 seconds is unacceptable, and we would rather just retry.
webRequest.KeepAlive = false;
webRequest.ProtocolVersion = HttpVersion.Version10;
webRequest.ServicePoint.Expect100Continue = false;
Anyone has any other idea?
edit:
ToString of the Exception: System.Net.WebException: The request was
aborted: The request was canceled. ---> System.Net.WebException: The
request was canceled at
System.Net.ServicePointManager.FindServicePoint(Uri address, IWebProxy
proxy, ProxyChain& chain, HttpAbortDelegate& abortDelegate, Int32&
abortState) at System.Net.HttpWebRequest.FindServicePoint(Boolean
forceFind) at
System.Net.HttpWebRequest.DoSubmitRequestProcessing(Exception&
exception) at System.Net.HttpWebRequest.SetResponse(Exception E) ---
End of inner exception stack trace --- at
System.Net.HttpWebRequest.GetResponse() at WebException message: The
request was aborted: The request was canceled.
edit2: And we are NOT reaching the limit. We know when that happens,
and the problem is NOT that. We have been doing this for two years,
and this thing only happened twice during the whole time. Per
AccessToken we are only doing 2-3 requests/minute, and the throttling
on Facebook is 600 requests/accesstoken/ip.
edit3: I would like to add an extra tip for people who have this or similar problem: Make sure that you dispose your RequestStream, your Response and your ResponseStream object.
http://www.dotnetframework.org/default.aspx/4#0/4#0/untmp/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/fx/src/Net/System/Net/ServicePointManager#cs/1305376/ServicePointManager#cs
I can see where the exception is thrown. Did you try increasing the HTTP request limit? The default is 2 per seconds.
ServicePointManager.DefaultConnectionLimit = 1000;
My Solve for Xamarin
public async Task<string> GetMessageEx(HttpWebResponse response)
{
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string result = await streamRead.ReadToEndAsync();
await streamResponse.FlushAsync();
return result;
}
I am using a payment gateway API in my ASP.Net application. When testing in MonoDevelop with XSP the application works. When I configure it to run in apache2 with mod_mono the code keeps crashing with a timeout error.
I am stumped as to what could change with hosting in Apache instead of XSP. Anyways below is the code that is timing out:
private string SubmitXml(string InputXml)
{
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(_WebServiceUrl);
webReq.Method = "POST";
byte[] reqBytes;
reqBytes = System.Text.Encoding.UTF8.GetBytes(InputXml);
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = reqBytes.Length;
webReq.Timeout = 5000;
Stream requestStream = webReq.GetRequestStream();
requestStream.Write(reqBytes, 0, reqBytes.Length);
requestStream.Close();
HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.ASCII))
{
return sr.ReadToEnd();
}
}
The code is crashing on the line: Stream requestStream = webReq.GetRequestStream();
The error returned is:
The request timed out
Description: HTTP 500. Error processing request.
Stack Trace:
System.Net.WebException: The request timed out at
System.Net.HttpWebRequest.GetRequestStream () [0x0005f] in
/private/tmp/monobuild/build/BUILD/mono-2.10.9/mcs/class/System/System.Net/HttpWebRequest.cs:746
at TCShared.PxPay.SubmitXml (System.String InputXml) [0x00048] in
/Users/liam/Projects/techcertain/techcertaincsharp/Components/TCShared/PaymentGateways/Client/PxPay.cs:85
at TCShared.PxPay.GenerateRequest (TCShared.RequestInput input)
[0x00015] in
/Users/liam/Projects/techcertain/techcertaincsharp/Components/TCShared/PaymentGateways/Client/PxPay.cs:69
In my Web.Config I have the following as the request timeout:
<httpRuntime executionTimeout="43200" maxRequestLength="104856" requestValidationMode="2.0" />
I have tried changing the Timeout value on the HttpWebRequest but it still is timing out.
What is causing this to happen and how can I fix it?
I managed to find out why I was experiencing this problem. It is completely unrelated to the use of Apache.
I am using Npgsql for database access to Postgresql. Npgsql comes with two dlls (Npgsql.dll and Mono.Security.dll). For some unknown reason Mono.Security.dll causes the HttpWebRequest to timeout when running on Mono.
Anyways Mono.Security.dll isn't needed when running on Mono because it is already included in the Mono framework. So after removing the Mono.Security dll from my bin directory HttpWebRequest's are now working.
Full credit goes to this post here http://mono.1490590.n4.nabble.com/The-request-timed-out-at-HttpWebRequest-EndGetResponse-td2218213.html .