C# POST and be transfered to another site (https) - c#

I am supposed to post some data to a site, using C#. I could post by just using a formular and simple html code. But I do not want any user to be able to look at the source code.
My basic code is:
WebRequest request = WebRequest.Create("https://blabla.bla");
request.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
request.Method = "POST";
try
{
request.ContentLength = bytes.Length;
request.GetRequestStream().Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
}
finally
{
if (request.GetRequestStream() != null)
{
request.GetRequestStream().Close();
}
}
This posts the data. But how would I do if I want to be transfered to the url and bringing the needed variables? Is it even possible? The site I want to be transfered to is a https.

If you want the user to end up at the page, you'll have to do the post from the client. This means the data has to be on the client. You could get the html of the page like you've done and write that out to the browser, but then if the user clicked anything or did anything with that rendered html, missing sessions/cookies etc could be a mess.
You could have a javascript function in an external minified/obfuscated js file that took in any necessary parameters, such that you build the form and submit it from that javascript function. Yes, a user could still figure out what is happening if they did deep enough, but the client browser has to know the data in order to send it. You have to find the trade-off between security and your userbase and their likelihood to dig into the source code.

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.

asp.net button onclick post to another page

I have a page in .Net that currently does some processing of info when a button is clicked. It posts back, updates some info and then redirects the user onwards.
What I want to do now is for this same button, when it's clicked, the info is updated but instead of a redirect it does a POST to another site. The reason being that this other site needs to read a bunch of data from the form I submit.
So, I know about the PostBackUrl property but that will stop the processing of the data that I need done.
So is there another way for me to be able to somehow combine both a postback that then becomes as POST to another site?
Or alternatively some way for me to be able to do the updates I need and then do a POST?
The suggested solutions all kind-of worked but the only one that actually did exactly what I needed it to was this one:
Link to SO answer
The reason the other answers above didn't work is that I was POSTing to a payment gateway and for whatever reason their system thought there was a problem with various missing fields in all solutions except the one I linked to. No idea why, I don't have access to their systems to know what they were actually doing.
In any case, thanks for all answers but have a look at the linked one if you're running into a similar issue.
if PostBack isn't absolutely needed, you can actually send them in the request query itself.
You can do a POST from codebehind, you can find details in this answer Redirect to another page using Post method from Code behind
If I got your question right I think you will need to get all the form data from Request.Form and make a HttpWebRequest to the other site:
string url = "http://anothersite.com/";
// create post data
StringBuilder postDataBuilder = new StringBuilder();
foreach (var key in this.Request.Form.AllKeys)
{
postDataBuilder.AppendFormat("{0}={1}&", this.Request.Form[key]);
}
string postData = postDataBuilder.ToString();
// create the web request for the POST
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
// add the post data
using (StreamWriter requestStream = new StreamWriter(webRequest.GetRequestStream()))
{
requestStream.Write(postData);
}
Hope this helps!

Load processed post javascript / ajax html into string

I am trying to load processed webpage into string, but seems like it is loading javascript as well; but I want this to be "the final" result that can he saved to static html file and run offline.
This is what I am doing at this moment
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textBox9.Text);
IWebProxy theProxy = request.Proxy;
if (theProxy != null)
{
theProxy.Credentials = CredentialCache.DefaultCredentials;
}
request.UseDefaultCredentials = true;
request.Proxy = WebRequest.DefaultWebProxy;
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
Any suggestions?
If I understand your post correctly, you don't want to strip the javascript out of the page, but keep it and make it so that it will execute just as though you had visited the page normally in a browser?
This is kind of a notoriously hard problem for proxies to overcome, and others have done it with varying degrees of success. Javascript that is embedded in the page should run just fine, but you will run into problems running any javascript that is loaded into a page from an external file.
One thing you could try is to rewrite the paths to external javascript libraries to reflect a local path, then grab copies of those javascript files over the network as well and store everything in a mimicked directory structure. Your milage may vary based on how fancy the javascript involved is, e.g. some ajax calls probably won't work no matter what you do.

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.

Reading and posting to web pages using C#

I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.
Small coding examples like the ones linked to at http://www.csharp-station.com/HowTo/HttpWebFetch.aspx tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.
For the record, I'm not building a malicious and/or spam related product.
So how do I go read web pages that require a few steps of normal browsing to reach first?
You can programmatically create an Http request and retrieve the response:
string uri = "http://www.google.com/search";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// encode the data to POST:
string postData = "q=searchterm&hl=en";
byte[] encodedData = new ASCIIEncoding().GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(encodedData, 0, encodedData.Length);
// send the request and get the response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do something with the response stream. As an example, we'll
// stream the response to the console via a 256 character buffer
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Char[] buffer = new Char[256];
int count = reader.Read(buffer, 0, 256);
while (count > 0)
{
Console.WriteLine(new String(buffer, 0, count));
count = reader.Read(buffer, 0, 256);
}
} // reader is disposed here
} // response is disposed here
Of course, this code will return an error since Google uses GET, not POST, for search queries.
This method will work if you are dealing with specific web pages, as the URLs and POST data are all basically hard-coded. If you needed something that was a little more dynamic, you'd have to:
Capture the page
Strip out the form
Create a POST string based on the form fields
FWIW, I think something like Perl or Python might be better suited to that sort of task.
edit: x-www-form-urlencoded
You might try Selenium. Record the actions in Firefox using Selenium IDE, save the script in C# format, then play them back using the Selenium RC C# wrapper. As others have mentioned you could also use System.Net.HttpWebRequest or System.Net.WebClient. If this is a desktop application see also System.Windows.Forms.WebBrowser.
Addendum: Similar to Selenium IDE and Selenium RC, which are Java-based, WatiN Test Recorder and WatiN are .NET-based.
What you need to do is keep retrieving and analyzing the html source for each page in the chain. For each page, you need to figure out what the form submission will look like and send a request that will match that to get the next page in the chain.
What I do is build a custom class the wraps System.Net.HttpWebRequest/HttpWebResponse, so retrieving pages is as simple as using System.Net.WebClient. However, my custom class also keeps the same cookie container across requests and makes it a little easier to send post data, customize the user agent, etc.
Depending on how the website works you can either manipulate the url to perform what you want. e.g to search for the word "beatles" you could just open a request to google.com?q=beetles and then just read the results.
Alternatively if the website does not use querystring values (url) to process page actions then you will need to work on a webrequest which posts the required values to the website instead. Search in Google for working with WebRequest and webresponse.

Categories