ASP.net Post with redirect? - c#

Basically I want to take a URLString and break out all variables and their values and Post them to another page with a redirect to taht page.. How do i pull this off without having a form and actuall submitting etc...
This is what i got..
string url = "http://www.blah.com/xyz.aspx";
StringBuilder postData = new StringBuilder();
postData.Append("CustomerID=" + HttpUtility.UrlEncode("Hello Rico") + "&");
postData.Append("FirstName=" + HttpUtility.UrlEncode("HelloFirstName"));
//ETC for all Form Elements
// Now to Send Data.
StreamWriter writer = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.ToString().Length;
try
{
writer = new StreamWriter(request.GetRequestStream());
writer.Write(postData.ToString());
writer.Flush();
HttpWebResponse WebResp = (HttpWebResponse)request.GetResponse();
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
Response.Write(_Answer.ReadToEnd());
}
finally
{
if (writer != null)
writer.Close();
}

Since you cannot redirect and post at the same time, your only option is to render an html page with a form that is submitted on page load. Unless you can make the receiver accept the parameters in the url of course. If it is an asp.net page you want to "post" to, it should not really matter if you send data in the querystring, unless of course you are sending massive amounts of data.
Remember that redirecting, is the same as telling the browser to "go to this page instead". This information is in the http header that you return. Therefore, there is not a lot of overhead in rendering a form that auto submits.

I'm not sure this is the right strategy - have you considered either HttpModules for manipulating requests or Server.Transfer for internal redirection?

What is it that you need the page you're redirecting the user toward to do? Your best option is to use Session Variables to pass the data between pages on Redirection unless you care to preserve the form that was initially passed to the page.
You can use code such as the following to add the information to a session item.
Session.Item("CustomerID") = "CustomerID=" & ID.ToString

Related

Post data from aspx page to mvc page

I am trying to post data from one page (aspx) to another (mvc). The way I am trying to go about it is in the code behind (aspx.cs) but so far the only way I have found to successfully redirect is to use:
Response.Redirect
which I can't use this because it apparently can only use GET (which won't work because the data I am wanting to transfer can potentially have too many characters for GET to handle). The other stipulation is that I can't use a session variable (the person I'm working with refuses to use session data).
I've looked into things like:
var tdd = new TempDataDictionary();
tdd.Add("subject",subject);
and
Context.Items["subject"] = subject;
but I'm not sure how I'd read that data in the other mvc controller Index method.
Use...
var data = //byte[] containing your data to post
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
request.ContentLength = data.Length;
requestStream.Write(data, 0, data.Length);
}
This is assuming you want to programmatically POST from the code behind.
Session wouldn't work going from one web app to another. It only works from one page to another in the same site.

Login to website using C#

Before everyone gets upset that this has been answered. I have scoured the web looking for how to do this and have tried a number of methods. Login to website, via C# and How to programmatically log in to a website to screenscape? Both of these were helpful but I cannot figure out why I cannot get past the login page. Here is my code:
string url = "https://www.advocare.com/login.aspx";
string url2 = "https://url.after.login";
HttpWebRequest wReq = WebRequest.Create(url) as HttpWebRequest;
wReq.KeepAlive = true;
wReq.Method = "POST";
wReq.AllowAutoRedirect = false;
wReq.ContentType = "application/x-www-form-urlencoded";
string postData = "ctl00$cphContent$txtUserName=Username&ctl00$cphContent$txtPassword=Password";
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
wReq.ContentLength = dataBytes.Length;
using (Stream postStream = wReq.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse;
string pageSource;
wReq = WebRequest.Create(url2) as HttpWebRequest;
wReq.CookieContainer = new CookieContainer();
wReq.CookieContainer.Add(wResp.Cookies);
HttpWebResponse wResp2 = wReq.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(wResp2.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Everytime I look at pageSource it is the HTML for the login.aspx page. I must be missing something here. Maybe it's not taking the cookie, I don't know. One question I have aside from, why doesn't this work, is in the string postData = "". Are those suppose to be the name or id portion of the html tag? Any help on this is greatly appreciated as I am stumped and will have to find a different way. I would like to continue with the WebRequest and WebResponse instead of using WebBrowser. If I can't, oh well. Thanks again for any help!
What are you trying to do besides login? If its like QAing a site programically, i would suggest using selenium andcreate a c# app based off of that. If u want i can post a link to a base project for a selenium based project.
Don't necessarily view the page source, but look at the actual HTTP POST. Install a HTTP proxy such as Fiddler and then re-visit the page you are trying to emulate. Complete the HTTP POST request, and check out the results produced in the proxy. From there you'll be able to see the actual parameters, cookies, headers, etc. that are being passed and you can then attempt to replicate this in your code. It's often easy to miss something when simply viewing the HTML source but monitoring the network traffic is pretty straight forward.

Communicating with an ASP website

I have a know a website that contains an open database of the result of an academic test.
http://nts.org.pk/NTSWeb/PPL_30Sep2012_Result/search.asp
I am expert with C# but newbie to web development.
Usually, using web browser, we can enter and roll number and server sends back the result. E.G. Use my Roll Num: 3912125
What I need to do is, use a C# application to communicate this roll null number and get anything, of my result. (any string is excepted, I will parse out my result from that string.)
How do I send query? when I don't know a list of possible query strings.
I tried this code:
string queryString = "RollNo=3912125";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"http://nts.org.pk/NTSWeb/PPL_30Sep2012_Result/search.asp");
request.UseDefaultCredentials = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] requestBytes = Encoding.UTF8.GetBytes(queryString);
request.ContentLength = requestBytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
}
WebResponse response = request.GetResponse();
textBox1.AppendText(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
textBox1.AppendText(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
You have to append the querystring to the url like this:
string queryString = "RollNo=3912125";
string url = String.Format(#"http://foo/search.asp?{0}", queryString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
You should take a look at the code in my answer to C# https login and download file. It gives a good demonstration of how to perform a POST request. As far as knowing what's valid to use for the query-formatted string in your POST, it's simply a matter of looking for appropriate input elements in the page content. It looks like what you have (RollNo) is correct. You may, however, need to also add the submit button value to your request as well depending on how the server behaves, giving you something like. RollNo=3912125&submit=submit.
You're most of the way there. Your queryString should look like RollNo=3912125&Submit=+Search+. When you are calling WebRequest.Create, the Url should in fact be http://nts.org.pk/NTSWeb/PPL_30Sep2012_Result/result.asp.
The rest of your code should work, though the answer #JamieSee recommended to you has some very good advice about wrapping things in using blocks correctly

Any workaround to get text in an iFrame on another domain in a WebBrowser?

You will probably first think is not possible because of XSS restrictions. But I'm trying to access this content from an application that hosts a WebBrowser, not from javascript code in a site.
I understand is not possible and should not be possible via non hacky means to access this content from javascript because this would be a big security issue. But it makes no sense to have this restriction from an application that hosts a WebBrowser. If I'd like to steel my application user's Facebook information, I could just do a Navigate("facebook.com") and do whatever I want in it. This is an application that hosts a WebBrowser, not a webpage.
Also, if you go with Google Chrome to any webpage that contains an iFrame whose source is in another domain and right click its content and click Inspect Element, it will show you the content. Even simpler, if you navigate to any webpage that contains an iFrame in another domain, you will see its content. If you can see it on the WebBrowser, then you should be able to access it programmatically, because it have to be somewhere in the memory.
Is there any way, not from the DOM objects because they seem to be based on the same engine as javascript and therefore restricted by XSS restrictions, but from some more low level objects such as MSHTML or SHDocVw, to access this text?
Can this be useful for you?
foreach (HtmlElement elm in webBrowser1.Document.GetElementsByTagName("iframe"))
{
string src = elm.GetAttribute("src");
if (src != null && src != "")
{
string content = new System.Net.WebClient().DownloadString(src); //or using HttpWebRequest
MessageBox.Show(content);
}
}
Do you just need a way to request content from code?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webRequest.URL);
request.UserAgent = webRequest.UserAgent;
request.ContentType = webRequest.ContentType;
request.Method = webRequest.Method;
if (webRequest.BytesToWrite != null && webRequest.BytesToWrite.Length > 0) {
Stream oStream = request.GetRequestStream();
oStream.Write(webRequest.BytesToWrite, 0, webRequest.BytesToWrite.Length);
oStream.Close();
}
// Send the request and get a response
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
// Read the response
StreamReader sr = new StreamReader(resp.GetResponseStream());
// return the response to the screen
string returnedValue = sr.ReadToEnd();
sr.Close();
resp.Close();
return returnedValue;

POST Data to PHP Page Using C# in Place of Form URL

I have an C# cart application that needs to POST some data to a PHP page and redirect the user to that page to view the data. Everything is working fine! So, what is the problem??
Since we are using a Javascript function to POST the form to the PHP page through setting its action to the PHP URL, it is not allowing us to clear our Session variable with our cart contents.
Once the user clicks checkout and is sent to the third party site, we want our session variable that stores their cart contents to go away. To my knowledge I cannot clear this via the Javascript, so my idea was to send the POST data and the user to the PHP page through the C# code.
When the user clicks checkout, the Javascript reloads the page, sets the cart data to a string variable, clears the session, then POSTs the data and sends the user to the PHP page.
All of this is working, except for the POST of data and redirecting the user. Unfortunately, the third party page cannot accept a URL.PHP?=var type parameter for security reasons, so we have to POST it.
Using WebRequest I believe I can get the data posted, but I cannot get the user redirected to that page to finish out their order. Any ideas?
I recommend you implement an intermediary page to prepare the data and cleanup the Session for you. The 'checkout' link would simply navigate the user to this intermediary page, which would do the following:
Collect the user's cart data out of the session
Clear the session
POST to the PHP page using WebRequest
From the MSDN on WebRequest:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main ()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
}
}
}
You can keep on using the Javascript solution and just add a Ajax call that will abandon the session
I am only speculating here but you should be able to transmit the data in a WebBrowser control item, that way it would send the post data and redirect.

Categories