Search Results

Search found 455 results on 19 pages for 'httpwebrequest'.

Page 5/19 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Difficulties with google authentication

    - by user283405
    I am trying to authenticate google with the following code but google sent me back to the login page again. //STEP# 1 string loginURL = "https://www.google.com/accounts/ServiceLoginBox?service=analytics&nui=1&hl=en-US&continue=https%3A%2F%2Fwww.google.com%2Fanalytics%2Fsettings%2F%3Fet%3Dreset%26hl%3Den%26et%3Dreset%26hl%3Den-US"; request = (HttpWebRequest)WebRequest.Create(loginURL); request.CookieContainer = cookieJar; request.Method = "GET"; request.KeepAlive = true; request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008111217 Fedora/3.0.4-1.fc10 Firefox/3.0.4"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); foreach (Cookie cook in response.Cookies) { cookieJar.Add(cook); } using (StreamReader sr = new StreamReader(response.GetResponseStream()) ) { serverResponse = sr.ReadToEnd(); sr.Close(); } galx = ExtractValue(serverResponse,"GALX","name=\"GALX\" value=\""); Console.WriteLine(galx); //Request# 2 string uriWithData = "https://www.google.com/accounts/ServiceLoginBoxAuth"; request = (HttpWebRequest)WebRequest.Create(uriWithData); request.KeepAlive = true; request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008111217 Fedora/3.0.4-1.fc10 Firefox/3.0.4"; request.Method = "POST"; request.CookieContainer = cookieJar; string param = string.Format("Email={0}&Passwd={1}&continue={2}&service=analytics&nui=1&dsh=8209101995200094904&GALX={3}&hl=en-US&PersistentCookie=yes","**my email address**",p,"",galx); byte[] postArr = StrToByteArray(param); request.ContentType = @"application/x-www-form-urlencoded"; request.ContentLength = param.Length; Stream reqStream = request.GetRequestStream(); reqStream.Write(postArr,0,postArr.Length); reqStream.Close(); response = (HttpWebResponse)request.GetResponse(); foreach (Cookie cook in response.Cookies) { cookieJar.Add(cook); } using (StreamReader sr = new StreamReader(response.GetResponseStream()) ) { serverResponse = sr.ReadToEnd(); Console.WriteLine(serverResponse); // Close and clean up the StreamReader sr.Close(); }

    Read the article

  • ASP.NET The underlying connection was closed: Could not establish trust relat

    - by David Lively
    When attempting to use HttpWebRequest to retrieve a page from my dev server, I get a web exception: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." The remote certificate is invalid according to the validation procedure... The url I'm attempting to read from is a plain-old http://myserver.com/mypage.asp - no SSL. The production server has a valid certificate so this shouldn't be an issue, but our dev server doesn't. Help!

    Read the article

  • C# HTTP Headers crafting

    - by rukqoa
    Since Http Headers can be crafted and customize, how would I change or modify the IP part of it using C# 's HttpWebRequest class. In other words, how can IP Spoofing be done using C#. Thanks for reading.

    Read the article

  • HttpWebResponse get mixed up when used inside multiple threads

    - by Holli
    In my Application I have a few threads who will get data from a web service. Basically I just open an URL and get an XML output. I have a few threads who do this continuously but with different URLs. Sometimes the results are mixed up. The XML output doesn't belong to the URL of a thread but to the URL of another thread. In each thread I create an instance of the class GetWebPage and call the method Get from this instance. The method is very simple and based mostly on code from the MSDN documentation. (See below. I removed my error handling here!) public string Get(string userAgent, string url, string user, string pass, int timeout, int readwriteTimeout, WebHeaderCollection whc) { string buffer = string.Empty; HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(url); if (!string.IsNullOrEmpty(userAgent)) myWebRequest.UserAgent = userAgent; myWebRequest.Timeout = timeout; myWebRequest.ReadWriteTimeout = readwriteTimeout; myWebRequest.Credentials = new NetworkCredential(user, pass); string[] headers = whc.AllKeys; foreach (string s in headers) { myWebRequest.Headers.Add(s, whc.Get(s)); } using (HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse()) { using (Stream ReceiveStream = myWebResponse.GetResponseStream()) { Encoding encode = Encoding.GetEncoding("utf-8"); StreamReader readStream = new StreamReader(ReceiveStream, encode); // Read 1024 characters at a time. Char[] read = new Char[1024]; int count = readStream.Read(read, 0, 1024); int break_counter = 0; while (count > 0 && break_counter < 10000) { String str = new String(read, 0, count); buffer += str; count = readStream.Read(read, 0, 1024); break_counter++; } } } return buffer; As you can see I have no public properties or any other shared resources. At least I don't see any. The url is the service I call in the internet and buffer is the XML Output from the server. Like I said I have multiple instances of this class/method in a few threads (10 to 12) and sometimes buffer does not belong the the url of the same thread but another thread.

    Read the article

  • Is it possible to authenticate on another website?

    - by Blankman
    If I am on a website#1, and I enter my username/pwd for website#2 on a login page that is on website#1, and website#1, behind the scenes, makes a httpwebrequest to website#2 and posts to the login page. If I then navigate to website#2, should I be logged in? website#2 uses formsauthentication and I call a httpHandler that is on website#2 and pass it the username/password via the querystring. Should this work?

    Read the article

  • Receicing POST data in ASP.NET

    - by grast
    Hi, I want to use ASP for code generation in a C# desktop application. To achieve this, I set up a simple host (derived from System.MarshalByRefObject) that processes a System.Web.Hosting.SimpleWorkerRequest via HttpRuntime.ProcessRequest. This processes the ASPX script specified by the incoming request (using System.Net.HttpListener to wait for requests). The client-part is represented by a System.ComponentModel.BackgroundWorker that builds the System.Net.HttpWebRequest and receives the response from the server. A simplified version of my client-part-code looks like this: private void SendRequest(object sender, DoWorkEventArgs e) { // create request with GET parameter var uri = "http://localhost:9876/test.aspx?getTest=321"; var request = (HttpWebRequest)WebRequest.Create(uri); // append POST parameter request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; var postData = Encoding.Default.GetBytes("postTest=654"); var postDataStream = request.GetRequestStream(); postDataStream.Write(postData, 0, postData.Length); // send request, wait for response and store/print content using (var response = (HttpWebResponse)request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { _processsedContent = reader.ReadToEnd(); Debug.Print(_processsedContent); } } } My server-part-code looks like this (without exception-handling etc.): public void ProcessRequests() { // HttpListener at http://localhost:9876/ var listener = SetupListener(); // SimpleHost created by ApplicationHost.CreateApplicationHost var host = SetupHost(); while (_running) { var context = listener.GetContext(); using (var writer = new StreamWriter(context.Response.OutputStream)) { // process ASP script and send response back to client host.ProcessRequest(GetPage(context), GetQuery(context), writer); } context.Response.Close(); } } So far all this works fine as long as I just use GET parameters. But when it comes to receiving POST data in my ASPX script I run into trouble. For testing I use the following script: // GET parameters are working: var getTest = Request.QueryString["getTest"]; Response.Write("getTest: " + getTest); // prints "getTest: 321" // don't know how to access POST parameters: var postTest1 = Request.Form["postTest"]; // Request.Form is empty?! Response.Write("postTest1: " + postTest1); // so this prints "postTest1: " var postTest2 = Request.Params["postTest"]; // Request.Params is empty?! Response.Write("postTest2: " + postTest2); // so this prints "postTest2: " It seems that the System.Web.HttpRequest object I'm dealing with in ASP does not contain any information about my POST parameter "postTest". I inspected it in debug mode and none of the members did contain neither the parameter-name "postTest" nor the parameter-value "654". I also tried the BinaryRead method of Request, but unfortunately it is empty. This corresponds to Request.InputStream==null and Request.ContentLength==0. And to make things really confusing the Request.HttpMethod member is set to "GET"?! To isolate the problem I tested the code by using a PHP script instead of the ASPX script. This is very simple: print_r($_GET); // prints all GET variables print_r($_POST); // prints all POST variables And the result is: Array ( [getTest] = 321 ) Array ( [postTest] = 654 ) So with the PHP script it works, I can access the POST data. Why does the ASPX script don't? What am I doing wrong? Is there a special accessor or method in the Response object? Can anyone give a hint or even know how to solve this? Thanks in advance.

    Read the article

  • Receiving POST data in ASP.NET

    - by grast
    Hi, I want to use ASP for code generation in a C# desktop application. To achieve this, I set up a simple host (derived from System.MarshalByRefObject) that processes a System.Web.Hosting.SimpleWorkerRequest via HttpRuntime.ProcessRequest. This processes the ASPX script specified by the incoming request (using System.Net.HttpListener to wait for requests). The client-part is represented by a System.ComponentModel.BackgroundWorker that builds the System.Net.HttpWebRequest and receives the response from the server. A simplified version of my client-part-code looks like this: private void SendRequest(object sender, DoWorkEventArgs e) { // create request with GET parameter var uri = "http://localhost:9876/test.aspx?getTest=321"; var request = (HttpWebRequest)WebRequest.Create(uri); // append POST parameter request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; var postData = Encoding.Default.GetBytes("postTest=654"); var postDataStream = request.GetRequestStream(); postDataStream.Write(postData, 0, postData.Length); // send request, wait for response and store/print content using (var response = (HttpWebResponse)request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { _processsedContent = reader.ReadToEnd(); Debug.Print(_processsedContent); } } } My server-part-code looks like this (without exception-handling etc.): public void ProcessRequests() { // HttpListener at http://localhost:9876/ var listener = SetupListener(); // SimpleHost created by ApplicationHost.CreateApplicationHost var host = SetupHost(); while (_running) { var context = listener.GetContext(); using (var writer = new StreamWriter(context.Response.OutputStream)) { // process ASP script and send response back to client host.ProcessRequest(GetPage(context), GetQuery(context), writer); } context.Response.Close(); } } So far all this works fine as long as I just use GET parameters. But when it comes to receiving POST data in my ASPX script I run into trouble. For testing I use the following script: // GET parameters are working: var getTest = Request.QueryString["getTest"]; Response.Write("getTest: " + getTest); // prints "getTest: 321" // don't know how to access POST parameters: var postTest1 = Request.Form["postTest"]; // Request.Form is empty?! Response.Write("postTest1: " + postTest1); // so this prints "postTest1: " var postTest2 = Request.Params["postTest"]; // Request.Params is empty?! Response.Write("postTest2: " + postTest2); // so this prints "postTest2: " It seems that the System.Web.HttpRequest object I'm dealing with in ASP does not contain any information about my POST parameter "postTest". I inspected it in debug mode and none of the members did contain neither the parameter-name "postTest" nor the parameter-value "654". I also tried the BinaryRead method of Request, but unfortunately it is empty. This corresponds to Request.InputStream==null and Request.ContentLength==0. And to make things really confusing the Request.HttpMethod member is set to "GET"?! To isolate the problem I tested the code by using a PHP script instead of the ASPX script. This is very simple: print_r($_GET); // prints all GET variables print_r($_POST); // prints all POST variables And the result is: Array ( [getTest] = 321 ) Array ( [postTest] = 654 ) So with the PHP script it works, I can access the POST data. Why does the ASPX script don't? What am I doing wrong? Is there a special accessor or method in the Response object? Can anyone give a hint or even know how to solve this? Thanks in advance.

    Read the article

  • Is it possible to use JSONP on the server?

    - by Denis Hoctor
    Hi all, I'm stuck on a clients host that has medium trust setup which blocks cross domain requests and need data from a 3rd party domain. I now have the option to use JSONP. I've used JSONP from the client with jQuery to get around the browsers cross domain security and I've used HttpWebRequest in ASP.Net 3.5. Is it possible to use JSON on the server and if so how? I don't think it is, but worth asking seeing as I already have this app written server side.... Thanks, Denis

    Read the article

  • Simulate Incorrect Content-Length Headers for HTTP in C#

    - by cfeduke
    We are building a comprehensive integration test framework in C# for our application which exists on top of HTTP using IIS7 to host our applications. As part of our integration tests we want to test incoming requests which will result in EndOfStreamExceptions ("Unable to read beyond end of stream") that occur when a client sends up a HTTP header indicating a larger body size than it actually transmits as part of the body. We want to test our error recovery code for this condition so we need to simulate these sorts of requests. I am looking for a .NET Fx-based socket library or custom HttpWebRequest replacement that specifically allows developers to simulate such conditions to add to our integration test suite. Does anyone know of any such libraries? A scriptable solution would work as well.

    Read the article

  • Programmatically automating a web login

    - by icemanind
    I am trying to create a C# Winforms application that will automatically log me into a site and download data. Specifically, I want to have my application automatically log into my online banking site, log me in, and download my transaction history. I can do this manually by logging in through a web browser and downloading it. I am trying to automate this. I know I probably need to use HttpWebRequest and HttpWebResponse. Does anyone have an example of this or a framework of the steps I need to take to accomplish this? Keep in mind it will be secure site (https) and I will somehow have to collect session information and retain the session information for the duration of the session. Any thoughts?

    Read the article

  • How to read the response stream before the Http response completes

    - by Marwan Aouida
    When making a request using HttpWebRequest object, I need to call the method GetResponse() to send the request and get the response back. The problem with this method is that it doesn't return the response object until all data has been received. Say I am downloading a 100 MB file, I won't be able to read it until the response finish and all the 100 MB is downloaded. What I want is to be able to read the response stream bytes as soon as they arrive, without waiting for the response to complete. I know I can use the Range Http header, but it won't work on my situation.

    Read the article

  • Mono - Uri class

    - by Jonathan.Peppers
    I am making an HttpWebRequest at a url similar to this: "http://mysite.com/search?query=my+search+string" Problem is, the Uri class escapes it with %, and the site I'm making the request against can't handle the escaped characters. (I have no control to fix the site) So tried this [Obsolete] constructor: new Uri(myUriString, true); But it did not seem to make any difference, when debugging, my Uri still got escaped. I am running this on a Mac with Mono, but I have not tried it on standard .Net on Windows to see if it has the same behavior. Is there another way to get around this issue?

    Read the article

  • Download office document without the web server trying to render it

    - by Dan Revell
    I'm trying to download an InfoPath template that's hosted on SharePoint. If I hit the url in internet explorer it asks me where to save it and I get the correct file on my disk. If I try to do this programmatically with WebClient or HttpWebRequest then I get HTML back instead. How can I make my request so that the web server returns the actual xsn file and doesn't try to render it in html. If internet explorer can do this then it's logical to think that I can too. I've tried setting the Accept property of the request to application/x-microsoft-InfoPathFormTemplate but that hasn't helped. It was a shot in the dark.

    Read the article

  • Posting data to a HttpHandler greater then ~29MB gives a 404 error

    - by Vaibhav Garg
    I am testing a HttpHandler that accepts XML. It works fine when a small amount of data is posted but if I post data larger then approx 29mb, I get a asp.net 404 Error. I am posting to the handler from another handler in the same project and I have tried 2 methods - 1. HttpWebRequest with "POST" 2. WebClient with UploadFile() and UploadData() I get the same 404 error when the posted data is above 29mb. I also tried putting a breakpoint right in the beginning of the receiving handler and debugging. It is never hit. Appears like the handler was never called. Works ok for smaller sized data. What am I doing Wrong? (Thanks in advance for helping)

    Read the article

  • Multi-threaded downloader in C# question

    - by blez
    Currently I have multi-threaded downloader class that uses HttpWebRequest/Response. All works fine, it's super fast, BUT.. the problem is that the data needs to be streamed while it's downloading to another app. That means that it must be streamed in the right order, the first chunk first, and then the next in the queue. Currently my downloader class is sync and Download() returns byte[]. In my async multi-threaded class I make for example, list with 4 empty elements (for slots) and I pass each index of the slot to each thread using the Download() function. That simulates synchronization, but that's not what I need. How should I do the queue thing, to make sure the data is streamed as soon as the first chunk start downloading.

    Read the article

  • Handling multiple async HTTP requests in Silverlight serially

    - by Jeb
    Due to the async nature of http access via WebClient or HttpWebRequest in Silverlight 4, when I want to do multiple http get/posts serially, I find myself writing code that looks like this: doFirstGet(someParams, () => { doSecondGet(someParams, () => { doThirdGet(... } }); Or something similar. I'll end up nesting subsequent calls within callbacks usually implemented using lambdas of some sort. Even if I break things out into Actions or separate methods, it still ends up being hard to read. Does anyone have a clean solution to executing multiple http requests in SL 4 serially? I don't need things to be synchronous, I just want serial execution.

    Read the article

  • How do I prevent an https response from throwing an AuthenticationException with Fiddler running?

    - by Ichabod Clay
    Relative newbie to C# here :) I'm currently creating a web link scraper and having issues with the responses I'm getting when trying to login to the website via my program. I'm trying to use Fiddler to see if my program is sending the proper data, but my program is throwing an AuthenticationException when trying to get a response from the site with Fiddler running. The requests are being sent over HTTPS and Fiddler's certificate is the cause of the excepting being thrown. My question is, what can I implement into my program to have it disregard the certificate authentication? As far as my program goes, the requests and responses are being handled by HttpWebRequest and HttpWebResponse classes.

    Read the article

  • Fails proceeding after POSTing to web server

    - by OverTheRainbow
    Hello According to this question, it seems like the error "Too many automatic redirections were attempted" is caused when forgetting to use a cookiecontainer to connect to a web server that uses cookies to keep track of the user. However, even though I used "request.CookieContainer = MyCookieContainer", I'm still getting into an endless loop that is terminated by VB Express with this error message. Imports System.IO Imports System.Net 'Remember to add reference to System.Web DLL Imports System.Web Imports System.Text Public Class Form1 Const ConnectURL = "http://www.acme.com/logon.php" Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim request As HttpWebRequest = WebRequest.Create(ConnectURL) 'Build POST data request.Method = "POST" request.ContentType = "application/x-www-form-urlencoded" Dim Data As New StringBuilder Data.Append("Account=" + HttpUtility.UrlEncode("jdoe")) Data.Append("&Password=" + HttpUtility.UrlEncode("test")) Dim byteData() As Byte byteData = UTF8Encoding.UTF8.GetBytes(Data.ToString()) request.ContentLength = byteData.Length Dim postStream As Stream = Nothing Try postStream = request.GetRequestStream() postStream.Write(byteData, 0, byteData.Length) Finally If Not postStream Is Nothing Then postStream.Close() End Try 'Dim MyCookieContainer As New CookieContainer Dim MyCookieContainer As CookieContainer = New CookieContainer() request.CookieContainer = MyCookieContainer 'Makes no difference 'request.KeepAlive = True 'request.AllowAutoRedirect = True Dim response As HttpWebResponse 'HERE '"Too many automatic redirections were attempted" response = request.GetResponse() Dim reader As StreamReader = New StreamReader(response.GetResponseStream()) RichTextBox1.Text = reader.ReadToEnd End Sub End Class This is probably a newbie issue, but I don't know what else to try. Any idea? Thank you for any hint.

    Read the article

  • HttpWebRequest.UserAgent : What does it do

    - by BDotA
    I read this MSDN like about it and ran its example. when I change the uSerAgnet to something like "blah", the output is wrong but when I use the same thing that is in the example of even when I comment out the line of code that is setting the UserASgent, the output is correct. what is UserAgent at all ? when should I set it ? How to know to what value should I set it ? thanks

    Read the article

  • VB.Net HTTPWebRequest Speed is slow comparing Python URLOpen

    - by regexhacks
    Hi I am coding a web-crawler which will crawl the websites and selectively parse different sections of a web site. I am a .Net developer so the choice was obvious that I did it in .Net but the speed was very slow which included downloading and parsing of HTMLPages Then I tried to just download the contents first using .Net and then same domains using python but the python was very impressive in downloading data. I have achieved downloading using python but the later part is not that easy to code in python, which obviously i don't want to do. The same batch of domain which took 100 seconds in Python was taking 20 minutes in .Net based crawler I tried http://www.eqlit.com/ to download and in took 8 seconds in Python and same was taking 100 Seconds in .Net crawler Does anyone anyone have any idea why this is slow in .Net but fast in python?

    Read the article

  • Streaming binary data to WCF rest service gives Bad Request (400) when content length is greater than 64k

    - by Mikey Cee
    I have a WCF service that takes a stream: [ServiceContract] public class UploadService : BaseService { [OperationContract] [WebInvoke(BodyStyle=WebMessageBodyStyle.Bare, Method=WebRequestMethods.Http.Post)] public void Upload(Stream data) { // etc. } } This method is to allow my Silverlight application to upload large binary files, the easiest way being to craft the HTTP request by hand from the client. Here is the code in the Silverlight client that does this: const int contentLength = 64 * 1024; // 64 Kb var request = (HttpWebRequest)WebRequest.Create("http://localhost:8732/UploadService/"); request.AllowWriteStreamBuffering = false; request.Method = WebRequestMethods.Http.Post; request.ContentType = "application/octet-stream"; request.ContentLength = contentLength; using (var outputStream = request.GetRequestStream()) { outputStream.Write(new byte[contentLength], 0, contentLength); outputStream.Flush(); using (var response = request.GetResponse()); } Now, in the case above, where I am streaming 64 kB of data (or less), this works OK and if I set a breakpoint in my WCF method, and I can examine the stream and see 64 kB worth of zeros - yay! The problem arises if I send anything more than 64 kB of data, for instance by changing the first line of my client code to the following: const int contentLength = 64 * 1024 + 1; // 64 kB + 1 B This now throws an exception when I call request.GetResponse(): The remote server returned an error: (400) Bad Request. In my WCF configuration I have set maxReceivedMessageSize, maxBufferSize and maxBufferPoolSize to 2147483647, but to no avail. Here are the relevant sections from my service's app.config: <service name="UploadService"> <endpoint address="" binding="webHttpBinding" bindingName="StreamedRequestWebBinding" contract="UploadService" behaviorConfiguration="webBehavior"> <identity> <dns value="localhost" /> </identity> </endpoint> <host> <baseAddresses> <add baseAddress="http://localhost:8732/UploadService/" /> </baseAddresses> </host> </service> <bindings> <webHttpBinding> <binding name="StreamedRequestWebBinding" bypassProxyOnLocal="true" useDefaultWebProxy="false" hostNameComparisonMode="WeakWildcard" sendTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:05:00" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" transferMode="StreamedRequest"> <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" /> </binding> </webHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="webBehavior"> <webHttp /> </behavior> <endpointBehaviors> </behaviors> How do I make my service accept more than 64 kB of streamed post data?

    Read the article

  • .NET WebRequest.PreAuthenticate not quite what it sounds like

    - by Rick Strahl
    I’ve run into the  problem a few times now: How to pre-authenticate .NET WebRequest calls doing an HTTP call to the server – essentially send authentication credentials on the very first request instead of waiting for a server challenge first? At first glance this sound like it should be easy: The .NET WebRequest object has a PreAuthenticate property which sounds like it should force authentication credentials to be sent on the first request. Looking at the MSDN example certainly looks like it does: http://msdn.microsoft.com/en-us/library/system.net.webrequest.preauthenticate.aspx Unfortunately the MSDN sample is wrong. As is the text of the Help topic which incorrectly leads you to believe that PreAuthenticate… wait for it - pre-authenticates. But it doesn’t allow you to set credentials that are sent on the first request. What this property actually does is quite different. It doesn’t send credentials on the first request but rather caches the credentials ONCE you have already authenticated once. Http Authentication is based on a challenge response mechanism typically where the client sends a request and the server responds with a 401 header requesting authentication. So the client sends a request like this: GET /wconnect/admin/wc.wc?_maintain~ShowStatus HTTP/1.1 Host: rasnote User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en,de;q=0.7,en-us;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive and the server responds with: HTTP/1.1 401 Unauthorized Cache-Control: private Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/7.5 WWW-Authenticate: basic realm=rasnote" X-AspNet-Version: 2.0.50727 WWW-Authenticate: Negotiate WWW-Authenticate: NTLM WWW-Authenticate: Basic realm="rasnote" X-Powered-By: ASP.NET Date: Tue, 27 Oct 2009 00:58:20 GMT Content-Length: 5163 plus the actual error message body. The client then is responsible for re-sending the current request with the authentication token information provided (in this case Basic Auth): GET /wconnect/admin/wc.wc?_maintain~ShowStatus HTTP/1.1 Host: rasnote User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en,de;q=0.7,en-us;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Cookie: TimeTrakker=2HJ1998WH06696; WebLogCommentUser=Rick Strahl|http://www.west-wind.com/|[email protected]; WebStoreUser=b8bd0ed9 Authorization: Basic cgsf12aDpkc2ZhZG1zMA== Once the authorization info is sent the server responds with the actual page result. Now if you use WebRequest (or WebClient) the default behavior is to re-authenticate on every request that requires authorization. This means if you look in  Fiddler or some other HTTP client Proxy that captures requests you’ll see that each request re-authenticates: Here are two requests fired back to back: and you can see the 401 challenge, the 200 response for both requests. If you watch this same conversation between a browser and a server you’ll notice that the first 401 is also there but the subsequent 401 requests are not present. WebRequest.PreAuthenticate And this is precisely what the WebRequest.PreAuthenticate property does: It’s a caching mechanism that caches the connection credentials for a given domain in the active process and resends it on subsequent requests. It does not send credentials on the first request but it will cache credentials on subsequent requests after authentication has succeeded: string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus"; HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; req.PreAuthenticate = true; req.Credentials = new NetworkCredential("rick", "secret", "rasnote"); req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; WebResponse resp = req.GetResponse(); resp.Close(); req = HttpWebRequest.Create(url) as HttpWebRequest; req.PreAuthenticate = true; req.Credentials = new NetworkCredential("rstrahl", "secret", "rasnote"); req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; resp = req.GetResponse(); which results in the desired sequence: where only the first request doesn’t send credentials. This is quite useful as it saves quite a few round trips to the server – bascially it saves one auth request request for every authenticated request you make. In most scenarios I think you’d want to send these credentials this way but one downside to this is that there’s no way to log out the client. Since the client always sends the credentials once authenticated only an explicit operation ON THE SERVER can undo the credentials by forcing another login explicitly (ie. re-challenging with a forced 401 request). Forcing Basic Authentication Credentials on the first Request On a few occasions I’ve needed to send credentials on a first request – mainly to some oddball third party Web Services (why you’d want to use Basic Auth on a Web Service is beyond me – don’t ask but it’s not uncommon in my experience). This is true of certain services that are using Basic Authentication (especially some Apache based Web Services) and REQUIRE that the authentication is sent right from the first request. No challenge first. Ugly but there it is. Now the following works only with Basic Authentication because it’s pretty straight forward to create the Basic Authorization ‘token’ in code since it’s just an unencrypted encoding of the user name and password into base64. As you might guess this is totally unsecure and should only be used when using HTTPS/SSL connections (i’m not in this example so I can capture the Fiddler trace and my local machine doesn’t have a cert installed, but for production apps ALWAYS use SSL with basic auth). The idea is that you simply add the required Authorization header to the request on your own along with the authorization string that encodes the username and password: string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus"; HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; string user = "rick"; string pwd = "secret"; string domain = "www.west-wind.com"; string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd)); req.PreAuthenticate = true; req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;req.Headers.Add("Authorization", auth); req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; WebResponse resp = req.GetResponse(); resp.Close(); This works and causes the request to immediately send auth information to the server. However, this only works with Basic Auth because you can actually create the authentication credentials easily on the client because it’s essentially clear text. The same doesn’t work for Windows or Digest authentication since you can’t easily create the authentication token on the client and send it to the server. Another issue with this approach is that PreAuthenticate has no effect when you manually force the authentication. As far as Web Request is concerned it never sent the authentication information so it’s not actually caching the value any longer. If you run 3 requests in a row like this: string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus"; HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; string user = "ricks"; string pwd = "secret"; string domain = "www.west-wind.com"; string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd)); req.PreAuthenticate = true; req.Headers.Add("Authorization", auth); req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; WebResponse resp = req.GetResponse(); resp.Close(); req = HttpWebRequest.Create(url) as HttpWebRequest; req.PreAuthenticate = true; req.Credentials = new NetworkCredential(user, pwd, domain); req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; resp = req.GetResponse(); resp.Close(); req = HttpWebRequest.Create(url) as HttpWebRequest; req.PreAuthenticate = true; req.Credentials = new NetworkCredential(user, pwd, domain); req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; resp = req.GetResponse(); you’ll find the trace looking like this: where the first request (the one we explicitly add the header to) authenticates, the second challenges, and any subsequent ones then use the PreAuthenticate credential caching. In effect you’ll end up with one extra 401 request in this scenario, which is still better than 401 challenges on each request. Getting Access to WebRequest in Classic .NET Web Service Clients If you’re running a classic .NET Web Service client (non-WCF) one issue with the above is how do you get access to the WebRequest to actually add the custom headers to do the custom Authentication described above? One easy way is to implement a partial class that allows you add headers with something like this: public partial class TaxService { protected NameValueCollection Headers = new NameValueCollection(); public void AddHttpHeader(string key, string value) { this.Headers.Add(key,value); } public void ClearHttpHeaders() { this.Headers.Clear(); } protected override WebRequest GetWebRequest(Uri uri) { HttpWebRequest request = (HttpWebRequest) base.GetWebRequest(uri); request.Headers.Add(this.Headers); return request; } } where TaxService is the name of the .NET generated proxy class. In code you can then call AddHttpHeader() anywhere to add additional headers which are sent as part of the GetWebRequest override. Nice and simple once you know where to hook it. For WCF there’s a bit more work involved by creating a message extension as described here: http://weblogs.asp.net/avnerk/archive/2006/04/26/Adding-custom-headers-to-every-WCF-call-_2D00_-a-solution.aspx. FWIW, I think that HTTP header manipulation should be readily available on any HTTP based Web Service client DIRECTLY without having to subclass or implement a special interface hook. But alas a little extra work is required in .NET to make this happen Not a Common Problem, but when it happens… This has been one of those issues that is really rare, but it’s bitten me on several occasions when dealing with oddball Web services – a couple of times in my own work interacting with various Web Services and a few times on customer projects that required interaction with credentials-first services. Since the servers determine the protocol, we don’t have a choice but to follow the protocol. Lovely following standards that implementers decide to ignore, isn’t it? :-}© Rick Strahl, West Wind Technologies, 2005-2010Posted in .NET  CSharp  Web Services  

    Read the article

  • How to Mock HttpWebRequest and HttpWebResponse using the Moq Framework?

    - by Nicholas
    How do you use the Moq Framework to Mock HttpWebRequest and HttpWebResponse in the following Unit Test? [Test] public void Verify_That_SiteMap_Urls_Are_Reachable() { // Arrange - simplified Uri uri = new Uri("http://www.google.com"); // Act HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Asset Assert.AreEqual("OK", response.StatusCode.ToString()); }

    Read the article

  • C# HttpListener Prefix issue with anything other than localhost

    - by jchristner
    Hello, I'm trying to use C# and HttpListener with a prefix of anything other than localhost and it fails (i.e. if I give it "server1", i.e. h t t p : / / l o c a l h o s t : 1 2 3 4 works, but h t t p : / / s e r v e r 1 : 1 2 3 4 fails (sorry, but the site thinks I'm trying to spam... the spaces are there because of that...) The code is... HttpListener listener = new HttpListener(); String prefix = "h t t p : / / s e r v e r 1 : 1 2 3 4/"; listener.Prefixes.Add(prefix); listener.Start(); The failure occurs on listener.Start() with an exception of "Access is denied.". Any ideas? Thanks!

    Read the article

  • The request was aborted: Could not create SSL/TLS secure channel.

    - by Simon
    We are enabled to connect to an https server using WebRequest because of this error message : The request was aborted: Could not create SSL/TLS secure channel. We know that the server aint got a valid https certificate with the path used (and we're not even sure if its fully release yet... ) but to bypass this issue, we use the following code that we've taken somewhere here in another post. [...] { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AllwaysGoodCertificate); } private static bool AllwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { return true; } There problem is that server just never valide the certificate and fail we the error ... Anyone have any idea of what should I do? Thank and sorry for my english ... I'm from Quebec and usualy talk french!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >