473,657 Members | 2,733 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# How to instruct a web server to cancel a request?

1 New Member
I'm writing an application that simplifies the interface to a few websites I use at my job. One of the web servers has a tendency to cause my program to throw a time out exception for a variety of reasons. This is an issue since this web site uses a persistent connection to keep you logged in. So if the request isn't finished and received by my program, the server keeps that open and after two time outs my program just becomes "hosed" and must be restarted. From my troubleshooting , I've found that after two times outs, the server puts roughly a 20 second delay before it returns a new request to you. After three time outs, this delay becomes roughly a minute. This is longer than my program's time out, but using a real web browser I could access the page, but only after a very long delay.

Is there a way to tell the server to abort the request(s) that timed out on the client so that these artificial delays do not happen? I've really had a hard time finding anything online about this. Most search results give me something about closing the request on the client only or SQL connections. I have tried closing the web request (not just the stream) and as you can see in the code below, closing the requests in the exceptions (although I'd think that would happen naturally when the function exited). I'm not really sure what else I could try and do.

If this is not possible, disconnecting my network connection and then reconnecting seems to fix the issue without restarting the program. Would there a way to tell my network adapter to close all connections with the site?

Expand|Select|Wrap|Line Numbers
  1.             private String SendRequestTo(String method, Byte[] requestBytes, Uri destination, String refer, NetworkCredential credentials, ThreadSource source)
  2.             {
  3.                 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(destination);
  4.                 webRequest.Method = method;
  5.                 webRequest.Accept = "*/*";
  6.                 webRequest.AllowAutoRedirect = false;
  7.                 webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12";
  8.                 webRequest.CookieContainer = new CookieContainer();
  9.                 webRequest.ContentLength = requestBytes.Length;
  10.                 webRequest.ContentType = "application/x-www-form-urlencoded";
  11.                 webRequest.PreAuthenticate = true;
  12.                 webRequest.Referer = refer;
  13.                 if (source == ThreadSource.WebCT || source == ThreadSource.Directory || source == ThreadSource.DLS || source == ThreadSource.VistaKeepAlive)
  14.                     webRequest.Timeout = 10000;
  15.  
  16.                 if (source == ThreadSource.Vista)
  17.                     webRequest.Timeout = 30000;
  18.  
  19.                 webRequest.Credentials = credentials;
  20.                 webRequest.CookieContainer.Add(cookies.GetCookies(destination));
  21.  
  22.                 Stream reqStream = null;
  23.                 StreamReader stream = null;
  24.                 HttpWebResponse webResponse = null;
  25.  
  26.                 try
  27.                 {
  28.                     if (method == "post")
  29.                     {
  30.                         reqStream = webRequest.GetRequestStream();
  31.                         reqStream.Write(requestBytes, 0, requestBytes.Length);
  32.                         reqStream.Close();
  33.                     }
  34.  
  35.                     webResponse = (HttpWebResponse)webRequest.GetResponse();
  36.                     if (webRequest.HaveResponse)
  37.                     {
  38.                         foreach (Cookie retCookie in webResponse.Cookies)
  39.                         {
  40.                             bool cookieFound = false;
  41.                             foreach (Cookie oldCookie in cookies.GetCookies(destination))
  42.                             {
  43.                                 if (retCookie.Name.Equals(oldCookie.Name))
  44.                                 {
  45.                                     oldCookie.Value = retCookie.Value;
  46.                                     cookieFound = true;
  47.                                 }
  48.                             }
  49.                             if (!cookieFound)
  50.                                 cookies.Add(retCookie);
  51.                         }
  52.  
  53.                         if ((webResponse.StatusCode == HttpStatusCode.Found) || (webResponse.StatusCode == HttpStatusCode.Redirect) || (webResponse.StatusCode == HttpStatusCode.Moved) || (webResponse.StatusCode == HttpStatusCode.MovedPermanently))
  54.                         {
  55.                             WebHeaderCollection headers = webResponse.Headers;
  56.                             return SendRequestTo(method, requestBytes, new Uri(headers["location"]), refer, credentials, source);
  57.                         }
  58.  
  59.                         stream = new StreamReader(webResponse.GetResponseStream());
  60.                         String responseString = stream.ReadToEnd();
  61.                         stream.Close();
  62.                         return responseString;
  63.                     }
  64.                 }
  65.                 catch (WebException e)
  66.                 {
  67.                     try
  68.                     {
  69.                         reqStream.Close();
  70.                     }
  71.                     catch (Exception)
  72.                     {
  73.                     }
  74.  
  75.                     try
  76.                     {
  77.                         stream.Close();
  78.                     }
  79.                     catch (Exception)
  80.                     {
  81.                     }
  82.  
  83.                     try
  84.                     {
  85.                         webResponse.Close();
  86.                     }
  87.                     catch (Exception)
  88.                     {
  89.                     }
  90.  
  91.                     throw new Exception("Exception occured while sending request.", e);
  92.                 }
  93.  
  94.                 throw new Exception("No response received from host.");
  95.             }
  96.  
Feb 19 '08 #1
0 1550

Sign in to post your reply or Sign up for a free account.

Similar topics

17
3258
by: Larry Woods | last post by:
I have a server page that has served an HTML page with a "Cancel" button on it, BUT this server page has not completed and is running a 15-30 second process before it completes. I want the browser user to be able to terminate the page before the server process has finished. What I tried was an onClick event that issued a "location.href..." in hopes that this would load this referenced page, etc. but I have found that the browser waits...
1
1883
by: Ryan McLean | last post by:
Hi everyone! What is happening is the method: sub_btnSubmitClicked is being executed every time any other object with a Handler is executed. I am trying not to use the withevents and handles method of adding handles to objects (I think that is where my problem lies) . . . sorry for the long post here is my codebehind and .aspx code. Thank you for any assistance anyone can offer! Ryan Public Class registration_report
4
1914
by: louise raisbeck | last post by:
I have this scenario (simplified) function addnewdata () { check for partial match already in db for information entered by user if (partialmatch succeeds) { open new window aspx page (using javascript) with a datagrid of these partial match records (by doing a sqlcommand using some query string values taken from opener data entered) *** }
6
2084
by: Ken Varn | last post by:
I have an ASP.NET form that may take a very long time to process a particular request. If the user closes the browser window, the request will continue to process until it completes. This is a problem when a user tries to re-establish a new session. Since the previous request is still being processed, the new request must now wait for it to complete. Is there anyway to force old IIS processing thread sessions to terminate if they are...
16
7939
by: wizard04 | last post by:
On my WinXP machine, with both IE6 and Firefox 1.0, response.redirect and server.transfer take about a minute. But on my WinNT machine with IE5.5, it works instantly. What's going on?
0
1233
by: Ken T. | last post by:
I have questions regarding what happens on the web server side during an asynchronous web method call when the client aborts its request via .Abort() call. Background: My client app asynchronously calls a web method in a "broker" web service that I've written. My broker service method in turn synchronously calls another web service to perform backend processing. This second, synchronous call can take up to a minute to return. My...
2
6947
by: Jobs | last post by:
Download the JAVA , .NET and SQL Server interview with answers Download the JAVA , .NET and SQL Server interview sheet and rate yourself. This will help you judge yourself are you really worth of attending interviews. If you own a company best way to judge if the candidate is worth of it. http://www.questpond.com/InterviewRatingSheet.zip
4
6213
by: AshishMishra16 | last post by:
HI friends, I am using the Flex to upload files to server. I m getting all the details about the file, but I m not able to upload it to Server. Here is the code i m using for both flex & for Struts: import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator;
0
8825
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7327
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4152
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.