How can I make a VERY simple web proxy using ASP.NET? - asp.net

I'm about to launch a site that was working well until I found the following hiccup:
I can't request a Yahoo! Pipe over SSL.
So the pages that require SSL are now missing a piece of their functionality unless I figure out a way around this; obviously, this could be done if I use an SSL-hosted page on my app to request the Yahoo! pipe for me.
I've seen solutions like http://www.iisproxy.net/license.html, but it seems to be a bit heavy for what I'm trying to do.
Can't I do this with a simple ASHX handler? Or is it more complex than that?
Thank you,
Michael

Thank you, John -- in case it's helpful to anyone else, here's the code I'm using in my ASHX file:
public override void ProcessRequest(HttpContext context)
{
var strURL = context.Server.UrlDecode(context.Request["url"]);
WebResponse objResponse = default(WebResponse);
WebRequest objRequest = default(WebRequest);
string result = null;
objRequest = HttpWebRequest.Create(strURL);
objResponse = objRequest.GetResponse();
StreamReader sr = new StreamReader(objResponse.GetResponseStream());
result = sr.ReadToEnd();
//clean up StreamReader
sr.Close();
//WRITE OUTPUT
context.Response.ContentType = "application/json";
context.Response.Write(result);
context.Response.Flush();
}
However, I was getting a couple extra characters (as opposed to the version that came direct from Yahoo! Pipes), so I had to remove those before parsing the JSON.

I guess if all you want to do is read the contents of a request you could use a WebRequest & WebResponse
here are some details on using that
http://www.west-wind.com/presentations/dotnetWebRequest/dotnetWebRequest.htm

Related

"Bypass" login of a php page sending username and password from asp.net

I'm developing an intranet (WRITTEN IN C#) which is going to gather all software applications used in my company. Some of these applications are not internal (so I can't actually see nor manage the source code).
I have to "bypass" a login page of an external application (WRITTEN IN PHP), sending username and password from asp.net (my intranet).
I don't really know HOW to manage this, IF possibile..
I only know that it's expecting a $_POST["l_username"] and a $_POST["l_passowrd"].
I've been looking for a solution for hours now..and still..nothing seems to be working. I read maaany post but there are not useful in my case.
EDIT 1:
public void sendInfo(string url, string data)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = data;
byte[] postBytes = Encoding.ASCII.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
req.AllowAutoRedirect = true;
}
This is the code I've been trying to use when I click on the link (I'm using a LinkButton)..but it is not redirecting me to the page. It's supposed to redirect, logging in using the parameters I give in Data and show me the main page of the external application..any suggestions would be greatly appreciated!
EDIT 2:
I found a code which seems to be working, finally!
You can find it ->HERE<-.
I tried it using a simple Web Form (with a LinkButton) and a class, it works perfectly.
My problem now is that my intranet uses a MasterPage, and when I'm calling the method from a Content Page..nothing happens.
What can I do to have this code working on a Content Page?
You can specify the POST method for WebRequest (more details in this SO answer: curl Request with ASP.NET )
You should build a Request with the ASP.net WebRequest. You know which data to send, so that shouldn't be a problem!
At the end I used this ->code here<- and it worked just fine.
Couldn't understand why it won't work using master and content pages, but I managed without them.

Reading posted JSON data in ASP.NET

I subscribe to a mass email service which, when an error occurs at their end, posts to a page on my website as an endpoint to notify me that an email has bounced.
They describe it as follows:
The event data is sent in the POST request body using a JSON object.
What I need to know is how can I capture the info posted to me?
Currently I'm pointing them to a generic handler, a .ashx page, this can be changed to whatever as long as it's in .NET.
In 10 years working with first classic ASP and now .NET I've never done this before and I must admit I don't even know where to start.
This is the code I used to achieve a similar thing - not sure where I got it originally.
C#
var strJSON = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
strJSON = inputStream.ReadToEnd();
}
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
object serJsonDetails = javaScriptSerializer.Deserialize(strJSON, typeof(object));
// go and process the serJsonDetails object
or VB
Dim strJSON = [String].Empty
context.Request.InputStream.Position = 0
Using inputStream = New StreamReader(context.Request.InputStream)
strJSON = inputStream.ReadToEnd()
End Using
Dim javaScriptSerializer As New JavaScriptSerializer()
Dim serJsonDetails As Object = javaScriptSerializer.Deserialize(strJSON, GetType(Object))
' go and process the serJsonDetails object
You could just read the Request stream (Request.GetRequestStream) and use Json.NET to deserialize to an object.
You could use MVC4 and the built in object mapping.
There's many options. Perhaps you should read up on them more so that you have an idea of their capabilities and drawbacks.
Probably Request.Form (here) will help you get the JSON, if you know the content of the post, and then you need something like json.net library to get the object, or you can simply search the string using regex or keywords
Or if you can direct the post to a web service(asmx) instead of a web page, those services will parse the json for you
If you need to read raw post data twice or many times, i advice you to use this code.
string postBodyJson = null;
MemoryStream ms = new MemoryStream();
Request.InputStream.Position = 0;
Request.InputStream.Seek(0, SeekOrigin.Begin);
Request.InputStream.CopyTo(ms);
ms.Position = 0;
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms))
{
postBodyJson = reader.ReadToEnd();
}

Xdocument.Load(XMLReader.Read()) Is giving me erros

I am trying to load a document see the code below
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
XmlReader responseReader = XmlReader.Create(response.GetResponseStream());
XDocument docs = XDocument.Load(responseReader.Read());
The above line is telling me xdocument.Load has some invalid arguments.
//XDocument docs = XDocument.Load(response.GetResponseStream());
This line is not loading anything Docs is empty
XDocument docs = XDocument.Load(responseReader);
This line is not giving any overload errors but returning nothing.
List<string> books = docs.Descendants("Test")....."Remaining QQuery"
Change
XDocument docs = XDocument.Load(responseReader.Read());
to
XDocument docs = XDocument.Load(responseReader);
The method for XDocument will accept an XmlReader which is what responseReader is, however you are calling the .Read() method on which only returns a boolean which is why you are getting that error.
Firstly, you almost had it without the XmlReader; you can't load the response straight into the XDocument, but, most of the time you can do:
XDocument docs = XDocument.Load(new StreamReader(response.GetResponseStream()));
Then check docs.Nodes.Count.
If docs is still empty, it's time to look at the response itself. Look at the response.ContentType - what is it?
Assuming the response isn't too large, look at it! You can do:
StreamReader reader = new StreamReader(response.GetResponseSteam());
string text = reader.ReadToEnd();
You can dump that string anywhere. Alternatively, if it is very big, you can save the response to disk, using either a FileStream with your Response, or, more simply WebClient.DownloadFile(url, path_to_save)
Either should be good enough to get you one step closer.

Need Help in converting Classic ASP Code to ASP.NET code

Set xml = Server.CreateObject("Microsoft.XMLHTTP")
xml.Open "GET", "http://www.indexguy.com/request_server.cfm?member_id=15893&id="+request.querystring("id")+"&"+request.querystring, False
xml.Send
How can I build the querystring parameter to a string object in C#/VB.NET
"member_id=15893&id="+request.querystring("id")+"&"+request.querystring"
If you are looking to build a querystring, String.Format("{0}", arg) might be a cleaner method to construct it.
For ASP.NET, you're going to want to replace the Server.CreateObject("Microsoft.XMLHTTP") with HttpWebRequest.
As for building the query string, that's still identical. You can still retrieve query string parameters by indexing into Request.QueryString. If you're using C# you can keep the + for string concatenation but might be more acceptable to use & in VB.
In ASP.NET the Page class exposes a Request property which provides access to a QueryString property - this is a NameValueCollection that lets you get values out in much the same way as in your existing example, by specifying keys:
var id = Page.Request.QueryString("id");
var newQuery = string.Format("?member_id=15893&id={0}&", id);
The above can easily be expanded to build more into your required query string.
As for the request you're initiating, that can be achieved using a WebRequest instance; to alter the sample from MSDN only slightly, here is an example:
WebRequest request = WebRequest.Create(yourUrl + newQuery);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Response.Write(response.StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd();
Response.Write(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();

Return XML as HTTP response

I've been given a seemingly simple task.
When a given URL is requested the response should simply be some valid XML.
How do I achieve this?
The URL will contain all the necessary code behind to get the data and construct the correct XML string. How do you then go ahead and manipulate the response to return this string only? The caller is receiving the XML string and populating a database with it, that's there responsibility I just need to provide this part of the project.
Thanks
Take a look at this :
Response.Clear();
Response.Write(yourXml);
Response.ContentType = "text/xml";
Response.End();
I would go for an HttpHandler. This way you circumvent all asp.net control creation etc. which is better for performance and seeing as you will not be outputting any html there's no point in using an actual aspx page.
Assuming you have your XML string created you can clear the response and just write your string out.
Response.Clear();
Response.ContentType = "text/xml";
Response.Write(myXMLString);
If you don't want to use full blown webservice then you could do something like this:
private void Page_Load(object sender, System.EventArgs e)
{
Response.ContentType = "text/xml";
//get data from somewhere...
Response.Write(data);
}
}
See here for something similar using images http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=325
Below is the way to send xml data to the browser as a response.
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.Append("<Books>");
xmlBuilder.Append("<Book>");
xmlBuilder.Append("Maths");
xmlBuilder.Append("</Book>");
xmlBuilder.Append("</Books>");
context.Response.ContentType = "text/xml";
context.Response.BinaryWrite(Encoding.UTF8.GetBytes(xmlBuilder.ToString()));
context.Response.End();

Resources