I am requesting a handler file from another handler file that returns an image, when I request my HttpWebRequest it takes more time to get the response. Here is my code, please help.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpCookie cookie = context.Request.Cookies["ASP.NET_SessionID"];
Cookie myCookie = new Cookie(cookie.Name, cookie.Value);
myCookie.Domain = url.Host;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(myCookie);
request.Timeout = 200000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
First make sure that your request is getting to the handler as quickly as possible. If not then it is some issue with your network. You can diagnose this with logs or debugging or whatever way you need. Use Fiddler to re-issue requests so you know exactly when it is fired and received.
If it is getting to the server and no processing on there is taking too much time then make sure that you are flushing and closing the response stream when you are finished writing to it. Also probably best to dispose of the responseStream object.
using(var responseStream = response.GetResponseStream()){
// write to the sucker
responseStream.Flush();
responseStream.Close();
}
NB If this is only on the first request (your question/answers are a little confusing) then try work out what exactly is happening at startup of the appdomain. Is there something big in global.asax - or is it doing a lot of DB work?
Related
I have built wcf. it is working well
The issue is when I call it many times it displays the following error:
The server encountered an error processing the request. See server
logs for more details
I configured a WCF Tracing File but it remains always empty. what can be the reason of this sudden stop of the service and how to fix it?
Here is the code that I use at the client's side every 20 seconds:
string url = "http://host/Service.svc/method";
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "GET";
ASCIIEncoding encoding = new ASCIIEncoding();
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
StreamReader loResponseStream =
new StreamReader(webresponse.GetResponseStream(), enc);
string strResult = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
I fixed the issue. it was due to open database connections. I missed to close, at the server side, the database connections. Thank you for answer
It could be a working memory issue on the server/host. If there's less than 5% available you get no response.
I just ran into a very strange behavior that I would like to understand. I am reading an image via HttpWebRequest. The following code raises a timeout exception:
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpWebRequest.Timeout = 5000;
HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream stream = httpWebReponse.GetResponseStream();
Please note that stream is not used anywhere else afterwards. However, if I add the following line:
Image image = Image.FromStream(stream);
Also here note that image is not used anywhere later on. Can anyone explain why I get the timeout in the first case?
I am working on a client that uses a webservice to get some events pushed its way - the webservice is designed so, that upon the client POST'ing a subscribe command, it will send back some events of interest and keep doing so as long as the client stay connected.
When POSTing the command, the service responds (immediately) with an initial answer with these headers
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Transfer-Encoding: chunked
and then keeps the connection open until it times out (after 30s, if the client does not send some keep-alive data)
Since it is a mix of POST + having to read the response + keeping the connection open until endOFStream, it appears I have to use HttpWebRequest with BeginGetRequestStream (to POST) and BeginGetResponse to read and act on the response.
My problem is that the BeginGetResponse callback is not called until the input stream is actually closed by the server/service (after 30s), despite AllowReadStreamBuffering being set to false.
The doc have this to say on AllowReadStreamBuffering:
The AllowReadStreamBuffering property affects when the callback from BeginGetResponse method is called. When the AllowReadStreamBuffering property is true, the callback is raised once the entire stream has been downloaded into memory. When the AllowReadStreamBuffering property is false, the callback is raised as soon as the stream is available for reading which may be before all data has arrived.
I've seen a few suggestions that no matter what AllowReadStreamBuffering is set to, HttpWebRequest will not call BeginGetResponse until it's buffer is filled up - but I have not been able to find anything on that in the docs.
Does any one have an idea on how to control this buffering behaviour or maybe suggestion to another approach I should try when dealing with this kind of webservice?
The relevant snippets of the code I currently use, look like this:
public void open()
{
string url = "http://funplaceontheinternet/webservice";
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
request.Credentials = new NetworkCredential("username", "password");
request.CookieContainer = new CookieContainer();
request.AllowReadStreamBuffering = false;
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
void GetRequestStreamCallback(IAsyncResult result)
{
Debug.WriteLine("open.GetRequestStreamCallback");
HttpWebRequest webRequest = (HttpWebRequest)result.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(result);
// Create the post data
byte[] byteArray = Encoding.UTF8.GetBytes(_xmlEncodedSubscribeCommand);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(BeginGetResponseCallback), webRequest);
}
void BeginGetResponseCallback(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = null;
if (request != null)
response = (HttpWebResponse)request.EndGetResponse(result);
else
Debug.WriteLine("request==null :-(");
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
Debug.WriteLine("BeginGetResponseCallback - received: " + line);
}
Debug.WriteLine("BeginGetResponseCallback - reader.EndOfStream");
}
}
else
Debug.WriteLine("response==null :-(");
}
You've mentioned that the service is a web service, but not which platform.
If this is a "normal" web service, then I assume that XML is the transport format.
If so, I suspect the problem may be that this style of communication does not really lend itself to streaming. The web service infrastructure at the server end might not be creating the SOAP envelope and payload until all the data is available. If you wanted to stream like this, you might be better using some custom service at the server end, rather than a web service.
Do you know for sure that the server is really streaming the response? (e.g confirmed with something like wireshark?)
If you really want to use a web service, then I would suggest you complete the request when the first event(s) are available, and don't wait for the timeout. This will still achieve the latency reduction that I assume you are trying to get.
When I am using HttpWebRequest and add this:
CookieContainer container = new CookieContainer();
request.CookieContainer = container;
it will throw an Operation Timeout exception in
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
If I don't add the CookieContainer the program runs without errors. Why doesn't this work?
I had this problem too. when I am requesting a Web Page and I put the HttpWebRequest in the Page_Load function and add cookie from current page into CookieContainer but it just hang in there till to timeout
the problem is when I first requesting the web page asp dot net just locked the session for protecting session being writing simultaneously from different place. when I try to call HttpWebRequest to request the same domain same Session it will be block till the first page end it's session lock, meanwhile, the first page is waiting for HttpWebRequest ends it job
the two request just waiting for each other till to timeout.
the good news is I found a way to solve this problem, I just set EnableSessionState="ReadOnly" in the first page, it makes first page that I call do not lock the session.
hope this can help someone.
How are you creating Request object??
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
CookieContainer
Try to set myWebRequest.Timeout =xxx
If you are running multiple concurrent requests try setting connections limit
System.Net.ServicePointManager.DefaultConnectionLimit
ServicePoint.ConnectionLimit
Check these links for more information:
HttpWebRequest "operation has timed out"
I need help setting .NET HttpWebRequest timeout
Adjusting HttpWebRequest Connection Timeout in C#
here are many reasons why GetResponse() might hang. Some are:
1) You have reached the connection limit on the client ( 2 conns per http/1.1 server, 4 connections per http/1.0 server, or custom limit set on the ServicePoint), and no connection is free to send a request to the server. In other words, you might have 2 requests outstanding (eg: to a 1.1 server) which are taking more than 2 minutes to complete, and then issue another GetResponse() to the same server. The last getresponse() might time out.
2) You have not closed the response stream of an earlier httpwebresponse. So, even if a connection is free, the request wont be sent.
3) The server is taking too long to send the response.
Situation 1:
There can be several reasons beind it. I wrote the following lines after reading about your problem and this code works,
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://google.com");
req.Method = "GET";
req.Timeout = 282;
CookieContainer cont = new CookieContainer();
req.CookieContainer = cont;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
Console.Write(reader.ReadToEnd());
}
resp.Close();
req.Abort();
Console.ReadLine();
I wrotereq.Timeout = 282;because i tested for several values and http://google.com does takes 282 milisecond from my computer to respond. From a slower internet connection, this code may return timeout.
Please be sure to set the time out high enough.
Situation 2:
May be the server you are connecting to takes little bit longer if it realize that cookie is enabled. When you don't set anything to req.CookieContainer then cookie is disabled. So please be sure about this fact. :) hope it will work.
My app currently uses OAuth to communicate with the Twitter API. Back in December, Twitter upped the rate limit for OAuth to 350 requests per hour. However, I am not seeing this. I am still getting 150 from the account/rate_limit_status method.
I was told that I needed to use the X-RateLimit-Limit HTTP header to get the new rate limit. However, in my code, I do not see that header.
Here is my code...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newURL);
request.Method = "GET";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
}
}
If I inspect the response, I can see that it has a property for Headers, and that there are 16 headers. However, I do not have X-RateLimit-Limit in the list.
(source: yfrog.com)
Any idea what I am doing wrong?
You should simple be able to use:
using (WebResponse response = request.GetResponse())
{
string limit = response.Headers["X-RateLimit-Limit"];
...
}
If that doesn't work as expected, you can do a watch on response.Headers and see what's in there.
Look at the raw response text (e.g., with Fiddler). If the header isn't there, no amount of C# code is going to make it appear. :) From what you've shown, it seems the header isn't in the response.
Update: When I go to: http://twitter.com/account/rate_limit_status.xml there is no X-RateLimit-Limit header. But when I go to http://twitter.com/statuses/public_timeline.xml, it's there. So I think you just need to use a different method.
It still says 150, though!