ASP HttpWebRequest and Redirect - c#

OK, I have a client doing a POST to a server with some data. The server receives the post, and answers with a redirect. The problem is that the client does not redirects. Also, I've tried to check the StatusCode of the response the client gets, and it is always the same "OK". Instead of the redirect code. What am I missing?
In the client side I have something like this:
StringBuilder sb;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/serv/Default.aspx");
request.Method = "POST";
byte[] data = Encoding.ASCII.GetBytes(GetDATA());
request.ContentType = "text/xml";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 10;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
response.Close(); } catch(Exception ex) {}
In the server side I have just this line:
HttpContext.Current.Response.Redirect("http://www.google.com", true);
In this case, the client receives an answer and does not do nothing.
Thanks.

When you have "AllowAutoRedirect" set to true, it means that your HttpWebRequest object will make a 2nd webrequest once it sees a redirect. When you see the "200 OK" from the response object, it is because you are seeing the response for "www.google.com". You can check the Response.ResponseURI to verify this.
You'll need to turn off the "AllowAutoRedirect", then check the response code like Oded said.

Related

HTTPWebRequest returns 401 unauthorized

I make a POST HTTPWebRequest to an URL to download a file. The problem is request fails with message authentication failed. But the same request made via POSTMAN app works fine. Error I receive is :
The remote server returned an error: (401) Unauthorized. Protocol Error.
The fiddler capture of requests between the two shows that POSTMAN has few additional ciphers, ec_point_formats, elliptic_curves, signature_algs. Not sure if that matters but in the interest of keeping this post short I am not giving the actual differences but can provided if asked for.
Sample code I use:
// create a request
HttpWebRequest request; = (HttpWebRequest)WebRequest.Create(inputUri);
SetProxy(inputProxyUri, inputProxyUser, inputProxyPassword, request);
request.ProtocolVersion = HttpVersion.Version11;
//Set authorization
string authorisation = string.Format("{0}:{1}", user, pass);
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authorisation));
string header = string.Format("{0} {1}", "Basic", encoded);
request.Headers[HttpRequestHeader.Authorization] = header;
request.KeepAlive = false;
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(requestParams);
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
//Get response stream
System.IO.Stream responseStream = ((HttpWebResponse)request.GetResponse()).GetResponseStream();
I have played with request object mentioned below :
request.ProtocolVersion = HttpVersion.Version11;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired;
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
request.Accept = "*/*";
Also changed registry to enable TLS 1.2, enable TLS-1.2 for client and server SCHANNEL communications as mentioned in https://www.derekseaman.com/2010/06/enable-tls-12-aes-256-and-sha-256-in.html without much luck.
Any help would be appreciated.

HTTP error 403 if POST is not used

I am trying to send protobuf data via REST from c# winform application. When I use the HTTP request with POST method( as shown in code below) it works perfect and returns "OK" status.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxx.execute-api.eu-west-1.amazonaws.com/test/input");
request.Headers["Authorization"] = "xxxyyyzzz"
request.Method = "POST";
request.ContentType = "application/octet-stream";
byte[] bytes = System.IO.File.ReadAllBytes("C:\\MyProtobuf.proto");
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
MessageBox.Show(myHttpWebResponse .StatusCode.ToString());
myHttpWebResponse .Close();
But if I simply want to check if website is alive or not using below code it gives me 403. Forbidden error.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxx.execute-api.eu-west-1.amazonaws.com/test/input");
request.Headers["Authorization"] = "xxxyyyzzz";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
MessageBox.Show(myHttpWebResponse .StatusCode.ToString());
myHttpWebResponse .Close();
what could be the possible reason for this error ?
your services serves POST method verb so you must call this service with post method, otherwise you should change your service methods to support get method.

Send and receive Json, cant read the response

I'm creating a application, and in one of it's functionalities I need to send json code over web request.
I use Get, Post, Put and Delete. And I already can create the connection and send and receive data.
But, for every request I should receive json code. Which I believe I am receiving, but I can't read it...
I'l put some code sample so you can see if there is something I can make to read that json code
First the Get request:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var response = (HttpWebResponse)webRequest.GetResponse ();
var responseString = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
webRequest.Abort();
return JArray.Parse (responseString);
This is the only case where I can read the json answer.
Next Post request:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var data = Encoding.UTF8.GetBytes(request);
webRequest.ContentLength = data.Length;
Stream stream = webRequest.GetRequestStream ();
stream.Write (data, 0, data.Length);
stream.Close ();
var response = (HttpWebResponse)webRequest.GetResponse();
webRequest.Abort();
return (int)response.StatusCode;
In this example I solved my problem using the response code.. which can only be 200, because every other code Is assumed as some exception.
For put and delete will be the same as post.
As I said I need to receive the json code. and not only the response code.
I would be really grateful if you could help-me in this problem.
Thanks to Orel who tried do help.
I got mt problem solved, I will post a sample code for everyone who might need this kind of solution.
My problem actually was very simple.
When I used "POST" in a web request I would create a stream to actually post my data. And then I would try to get my answer from that same stream, when actually I was getting the information I needed In the webRequest var.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var data = Encoding.UTF8.GetBytes(request);
webRequest.ContentLength = data.Length;
Stream stream = webRequest.GetRequestStream ();
stream.Write (data, 0, data.Length);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var responseString = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
stream.Close ();webRequest.Abort();
return JObject.Parse(responseString);

403 error response when submitting a post request to Instagram

I'm trying to "programmatically" login to Instagram with a HTTP post request. Although, whenever I try to do it to this URL: https://instagram.com/accounts/login/ - it gives me a 404 error. However, if I remove the slash from the end, e.g. /accounts/login, then it will work, however, the response body just seems to be a simple GET request as they simply just output the same as if it was a GET request. I'm actually expecting an error message as response.
The code is written in C# and is nothing fancy; basically a http web request and then I write the post data in the TCP stream. The website is using a CSRF token which needs to be included in the post request, so I first grab this key by using a simple GET request, and then continuing with the POST.
Is there any technical aspect that I'm missing? I've tried the code and done the same on several other websites and all attempts were successful.
The code looks much like this (same problem):
WebResponse Response;
HttpWebRequest Request;
Uri url = new Uri("https://instagram.com/accounts/login/");
CookieContainer cookieContainer = new CookieContainer();
Request = (HttpWebRequest)WebRequest.Create(url);
Request.Method = "GET";
Request.CookieContainer = cookieContainer;
// Get the first response to obtain the cookie where you will find the "csrfmiddlewaretoken" value
Response = Request.GetResponse();
string Parametros = "csrfmiddlewaretoken=" + cookieContainer.GetCookies(url)["csrftoken"].Value + "&username=USER&password=PASSWORD&next="; // This whill set the correct url to access
Request = (HttpWebRequest)WebRequest.Create(url); // it is important to use the same url used for the first request
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.UserAgent = "Other";
// Place the cookie container to obtain the new cookies for further access
Request.CookieContainer = cookieContainer;
Request.Headers.Add("Cookie",Response.Headers.Get("Set-Cookie")); // This is the most important step, you have to place the cookies at the header (without this line you will get the 403 Forbidden exception
byte[] byteArray = Encoding.UTF8.GetBytes(Parametros);
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
Response = Request.GetResponse(); // Fails here
Thanks in advance!

Unable to retrieve message body on server-side from HTTP Post

I am sending an HTTP post request using HTTPWebRequest to an URL. I am sending the post data using multipart/form-data content type along with the content length of the body. However, on the server side, I am unable to retrieve the body. I can only see the headers sent. The content length of the body I sent also matches.
Why am I not able to retrieve the body.
The request method looks like this:
public void Reset(string originalFileData, string uploadLocation)
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(Server), portNo);
client.Connect(serverEndPoint);
string responseContent;
string serverUrl = "http://" + Server + ":" + portNo + "/abc.aspx" + "?uplvar=" + uploadLocation;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl);
request.ContentType = "multipart/form-data";
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string postData = originalFileData;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
}
Edit: I forgot to mention, I am able to retrieve the body on the first time I send the request, but on any subsequent requests I send, I am not able to retrieve it. I am creating a new connection each time I send a request. So, something might be preventing the request body from being retrieved. I am not sure why.
Try replacing
request.ContentType = "multipart/form-data";
with
request.ContentType = "application/x-www-form-urlencoded";
or check this SO answer for code which works with multipart/formdata.

Categories

Resources