ASP.NET JSON response without web service - asp.net

I've got an ASP.NET based website that already has the necessary hooks into my back-end database and I want to write something really simple to return a small bit of JSON based on a URL parameter.
So, for example:
http://example.com/JSON/GetInfo.aspx?prodID=1234
And it would return some JSON with product details for the given ID.
I conceptually know how to do this from any ASPX page but I'm wondering if this is the right way to do it? (Assuming I would just be writing JSON back out to the response instead of HTML)
I don't need (or want) a full on .NET web service, just something that I could call from other pages on my site as well as one of our applications with a GET request to retrieve the desired info.
In visual studio, when I'm adding a new file what type should I use?

You should use a Generic Web Handler for this. It's a lightweight web component that you can call from any client code on your site.
Your url would looks like this
http://example.com/JSON/GetInfo.ashx?prodID=1234

Look into to ASP.Net Web Methods
http://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.90).aspx

Wouldn't an ordinary .aspx file do this?
string s= "{\"data\":\"test\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(s);
Response.End();

Create your aspx page "GetInfo.aspx"
In your Page_Load :
string myID = request.QueryString["prodID"];
string myJson = "";
//Fill your JSON with database, ...
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(myJson);
Response.End();
That will returning your JSON

Related

get a website data and display on my web page

I am Trying to display a website portion on my web page.and for this i dnt want to use iframe.But any other idea which can get data from a website and then display it on my web page like.
this is website
http://www.sugaronline.com/
and want to display this portion on m y web page
http://i.stack.imgur.com/CVsrh.jpg
Please any one tell me is there any way to do this except using iframe?
Update
Shared Function GetHtmlPage(ByVal strURL As String) As String
Dim strResult As String
Dim objResponse As WebResponse
Dim objRequest As WebRequest = HttpWebRequest.Create(strURL)
objResponse = objRequest.GetResponse()
Using sr As New StreamReader(objResponse.GetResponseStream())
strResult = sr.ReadToEnd()
sr.Close()
End Using
Return strResult
End Function
Dim responses As String = GetHtmlPage(theurl)
Refer existing posts
Using HTTPWebRequest in ASP.NET VB
or simply Google this
If you are using PHP, try using CURL, it is a server side request which fetches the data from the target site and then you can embed it in your page.
On the other hand, if you are using .Net, you can use httpwebrequest to do the same.
In short, you will have to make a server side request from your server to the target website to fetch the data and you can embed that data on your page as if it has come from your website.
Please check out this post
How to use httpwebrequest to pull image from website to local file
Here all you need to do is
when you have the image bytes ready, you need to write those bytes to response but before that, you will have to send proper headers to let the browser understand that you are now going to send the image.

using web sites to transfer xml

How do I setup a scenario where one website hosted at X publishes a URL that when browsed to will return purely XML.
A web page elsewhere is going to hit this URL, load the XML into objects.
So I want a url like http://www.xml.com/document.aspx?id=1
Another site will use webresponse and webrequest objects to get the response from the above page, I want the response to be good XML so I can just use the XML to populate objects.
I did get something working but the response contained all the HTML required to render the page and I actually just want XML as the response.
Probably the best way to this is with a HttpHandler/ASHX file, but if you want to do it with a page it's perfectly possible. The two key points are:
Use an empty page. All you want in the markup for your ASPX is the
<% Page ... %> directive.
Set the ContentType of the Response stream
to XML - Response.ContentType = "text/xml"
How you generate the XML itself is up to you, but if the XML represents an object graph, you can use an XmlSerializer (from the System.Xml.Serialization namespace) to write the XML directly to the Response stream for you e.g.
using System.Xml.Serialization;
// New up a serialiser, passing in the System.Type we want to serialize
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
// Set the ContentType
Response.ContentType = "text/xml";
// Serialise the object to XML and pass it to the Response stream
// to be returned to the client
serialzer.Serialize(Response.Output, MyObject);
If you already have the XML, then once you've set the ContentType, you just need to write it to the Response stream and then end and flush the stream.
// Set the ContentType
Response.ContentType = "text/xml";
Response.Write(myXmlString);
Response.Flush();
Response.End();

Retrieving HTML from ASP.NET page on postback

I've found a few posts about retrieving HTML from an ASPX page, mostly by overriding the render method, using a WebClient, or creating an HttpWebRequest. All these methods return the HTML of the page as it's loaded, but I was hoping to actually retrieve the HTML after the user has entered information.
The purpose behind this is that I work in IT, and I'm attempting to build a logging library that has an overload that essentially does a "screen-scrape" on the page just as the user encounters an exception, that way I can log the exception, and create an HTML file in a sub-directory of the logging directory that shows the page exactly as the user had it before clicking "submit" or having some other random error, and add an "ID" to the error that's logged telling whoever is fixing the issue which page to look at.
I hope I've provided enough information, because I really have no idea where to start.
Also, We'd like to do this through our own library, because our logging library is included in our common library, and many of our common library functions use our logging class.
Hmmm...
If you want to see what the user sees after they've been using the page, you're most likely going to have to do some fancy client-side scripting.
A naive approach:
When the clicks the submit button, fire a JavaScript event that encodes the DOM and either passes it as a form variable to the server, or executes a separate AJAX request with the encoded data as a parameter. ("Encode" in this case may be as simple as grabbing document.innerHtml, but I haven't checked.)
This potentially introduces a lot of overhead to every form submission, so I'd keep it out of production code.
I'm not sure why you need the rendered HTML as part of your exception log - I've never found it necessary for server-side debugging.
You getting HTML code from a website. You can use code like this.
string urlAddress = "http://www.jobdoor.in";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}

HTTP POST - I'm stuck

I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in HTTP Headers.
The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like
Request.Headers.Add(key,value);
but I cannot (exception from the framework); I tried the other way around, using the Response object like
Response.AppendHeader("key", "value");
and then redirect to the page... but this doesn't work, as well.
It's evident, I think, that I'm stuck there, any help?
EDIT I forgot to tell you that my environment is .Net 2.0, c#, on Win server 2003.
The exception I got is
System.PlatformNotSupportedException was unhandled by user code
Message="Operation is not supported on this platform."
Source="System.Web"
This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this.
Have you tried the WebClient class? An example might look like:
WebClient client = new WebClient();
NameValueCollection data = new NameValueCollection();
data["var1"] = "var1";
client.UploadValues("http://somewhere.com/api", "POST", data);
Like #lassevk said, a redirect won't work.
You should use the WebRequest class to do an HTTP POST from your page or application. There's an example here.
Take a look at HttpWebRequest. You should be able to construct a request to the URL in question using HttpWebRequest.Method = "POST".
You should post more information.
For instance, is this C#? It looks like it, but I might be wrong.
Also, you say you get an exception, what is the exception type and message?
In any case, you can't redirect to a page for POST, you need to submit it from the browser, not from the server redirect, so if you want to automate this, I would guess you would need to generate a html page with a form tag, with some hidden input fields, and then submit it with javascript.
I think they mean they don't want you to use URL parameters (GET). If you use http headers, it's not really querying through POST any more.
What language/framework?
Using Python and httplib2, you should be able to do something like:
http = httplib2.Http()
http.request(url, 'POST', headers={'key': 'value'}, body=urllib.urlencode(''))
I believe that the Request object would only accept a certain set of predefined headers.
There's an enumeration that lists all the supported HTTP Headers too.
But I can't remember it at the moment... I'll look it up in a sec...
I tested your scenario using 2 sample pages using XmlHttpRequest option.
Custom headers are available in the aspx page posted to, using XmlHttpRequest.
Create the following 2 pages. Make sure the aspx page is in a solution , so that you can run the in the debugger, set break point and inspect the Request.Header collection.
<html>
<head>
< script language="javascript">
function SendRequest()
{
var r = new XMLHttpRequest();
r.open('get', 'http://localhost/TestSite/CheckHeader.aspx');
r.setRequestHeader('X-Test', 'one');
r.setRequestHeader('X-Test', 'two');
r.send(null);
}
< script / >
</head>
<body>
<form>
<input type="button" value="Click Me" OnClick="SendRequest();" />
</form>
</body>
</html>
CheckHeader.aspx
using System;
using System.Web;
using System.Web.UI;
public partial class CheckHeader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string value = string.Empty;
foreach (string key in Request.Headers)
value = Request.Headers[key].ToString();
}
}
Man.. This html editor sucks.. or i do not know how to use it...
The exception I was facing yesterday was caused by my stupid try to write on the headers of the already built page.
When I started creating my Request following one of the mothods indicated here, I could write my headers.
Now I'm using the WebRequest object, as in the sample indicated by #sectrean, here.
Thanks a lot to everybody. StackOverflow rocks :-)

Process raw HTTP request content

I am doing an e-commerce solution in ASP.NET which uses PayPal's Website Payments Standard service. Together with that I use a service they offer (Payment Data Transfer) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form :
SUCCESS
first_name=Jane+Doe
last_name=Smith
payment_status=Completed
payer_email=janedoesmith%40hotmail.com
payment_gross=3.99
mc_currency=USD
custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham
Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done.
Something like this placed in your onload event.
if (Request.RequestType == "POST")
{
using (StreamReader sr = new StreamReader(Request.InputStream))
{
if (sr.ReadLine() == "SUCCESS")
{
/* Do your parsing here */
}
}
}
Mind you that they might want some special sort of response to (ie; not your full webpage), so you might do something like this after you're done parsing.
Response.Clear();
Response.ContentType = "text/plain";
Response.Write("Thanks!");
Response.End();
Update: this should be done in a Generic Handler (.ashx) file in order to avoid a great deal of overhead from the page model. Check out this article for more information about .ashx files
Use an IHttpHandler and avoid the Page model overhead (which you don't need), but use Request.Form to get the values so you don't have to parse name value pairs yourself. Just pretend you're in PHP or Classic ASP (or ASP.NET MVC, for that matter). ;)
I'd strongly recommend saving each request to some file.
This way, you can always go back to the actual contents of it later. You can thank me later, when you find that hostile-endian, koi-8 encoded, [...], whatever it was that stumped your parser...
Well if the incoming data is in a standard form encoded POST format, then using the Request.Form array will give you all the data in a nice to handle manner.
If not then I can't see any way other than using Request.InputStream.
If I'm reading your question right, I think you're looking for the InputStream property on the Request object. Keep in mind that this is a firehose stream, so you can't reset it.

Resources