What's the easiest way to get a web request into C# code? - asp.net

So... I've got an ASP.NET app. Let's assume I configure IIS to always point to the same file, index.aspx. Let's say I want to write all my code in C# and then return some HTML I generated in the C#. How do I do that?
Would I just have 1 file with 1 line of code,
<%# Page CodeBehind="mycode.cs"
Is it necessary to have such a "useless" file? I can't direct the request straight into the code-behind?
Secondly, where are some good tutorials on code-behinds? Specifically, I see this Page_Load event that I guess gets called automatically?
Are there other events? What are they?
Also, how would I access things like POST data, or the request URL?
How would I return a HTML response? Or a 404?
I'm seeing a lot of tutorials on "inline" ASP, but I don't really care about that.

Sounds like you want a generic handler. They are available in the New Item... dialog. This will give you a .ashx file where you can handle incoming web requests just like you would in your scenario, but in a cleaner way. Using these you can return any kind of HTTP response, including HTTP errors. You have full access to the HTTP context for POST data, URL parameters, cookies, etc. See more here.
Another alternative is to implement IHttpHandler yourself, although with generic handlers there isn't much point in going through the effort.

Are there other events? What are they?
There is a whole lot of Events available when you inherit from System.Web.UI.Page. You can see them http://msdn.microsoft.com/en-us/library/ms178472.aspx
Also, how would I access things like POST data, or the request URL?
this.Request.Form, would let you access the PostData from a page. this.Request.Url would let you access the url.
How would I return a HTML response? Or a 404?
You can override the Render method of the page to provide HTML Response. You can throw a HttpException(404, "file not found") to return 404.
After going through your questions, you most likely need ASP.NET MVC rather than ASP.NET webforms or you can use a handler as suggested by Martin

Related

Javascript to handle a form return

I have a standard html registration page that targets an external .asp page on submit.
What happens is that currently the .asp (which I don't have access to)returns an entire html page.
Instead I would like to somehow parse the returned html and populate the existing form with either
a) validation errors if incorrect
or
B) some sort of success message if all validated
Can anyone tell me if this is possible and or help with some pseudo code?
This is doable in JavaScript using ajax, but it requires that the ASP page (presumably on a different domain) sends appropriate CORS HTTP headers. Even if you don't have access to the actual ASP page, you may be able to get someone to setup the headers in IIS on their server.
Otherwise, you're stuck moving everything server-side, i.e. simulating the POST on your own webserver, and scraping the HTML to get the status back. That looks something like:
Postback the page to your own page (or use Ajax)
On your server, initiate a web request post of the data to the ASP page
Parse the results in your server code
Return an appropriate response to the browser client
The best you can do, assuming I'm interpreting your question correctly, is "scrape" the HTML returned from the asp page and make proper assumptions about the location and meaning of the text within the markup. I, personally, would strongly advise against developing anything of any kind of robustness based on what amounts to screen scraping, especially considering you don't have access to the .asp file itself. If I've misunderstood your problem, my apologies.

What is the ASP.NET equivalent of setting a request attribute in Java?

I have some functionality in the code behind, which after executing needs to forward the request to another page. I want to pass along data like you would by setting a request attribute in Java (i.e. - I don't want it in the query string of the redirected response). Is this possible with ASP.NET (c#)?
You can use Server.Transfer if you want to forward the request and keep all of the Request variables, or you can use Session.
Are you using ASP.NET Webforms or MVC? The following will redirect your request to a new page. You'll have to test and see if it forwards post data (I'm not sure). Now that you mention it, I don't think ASP.NET has a built in "forward:" request like java does. I think it just has "redirect" for security reasons. (Someone correct me if I'm wrong).
In Webforms:
try Response.Redirect("mynewpage").
In MVC:
at the completion of your action method return Redirect("mynewpage")
I don't know your use case, but it is generally not good practice to pass post data to a different page/request. Typically the posted action will take care of persistence, and then a GET request will be issued to the redirect page. If the redirected view needs access to the posted data, it should go to the persistence mechanism (DB) to retrieve it. This method is more secure, and generally better practice. This is a very general guideline, so use it as your needs allow.
HTH
Yes - See the reflection code at:
HttpModule to add headers to request
However - the question is - do you really want to use request headers? probably not. its a hack to use them. If you simply want to pass information, use the Context.Items dictionary to transfer your items between requests with Server.Transfer.
Depending on what you are doing and where your events are, you can also make use of Cross Page Postback.
See http://msdn.microsoft.com/en-us/library/ms178139.aspx
Otherwise, I'd go with vcsjones answer of Server.Transfer

Respond to HTTP Post in ASP.Net

I'd like to respond to an HTTP POST in an ASP.Net page.
I've found loads of example of sending an WebRequest, and I can successfully pick that up and read it in my Page_Load.
However, I'd like to then put some data back in the Response, but I can't find any examples of how to do this.
The actual requirement is for an external site to POST to a page and receive back a GUID for their records.
Any help very gratefully received.
It sounds like you should be using an HttpHandler and not a Page.
You create an HttpHandler by implementing the IHttpHandler interface. When implementing the IHttpHandler interface, you have full control over the response in the ProcessRequest method.
Typically ASP.NET page will put its rendered markup (html generated by controls present on it) in response. Going by your requirement, I would suggest you to use generic HTTP handler (.ashx file) that will give you complete control over your response.
See this article for quickstart with ashx: http://www.brainbell.com/tutorials/ASP/Generic_Handlers_(ASHX_Files).html

Receive requests with a .asmx file or a .aspx file?

I'm setting up my site to receive info from people via text message. The way it works is they text a number, that service then sends an HTTP POST to a url I specify. I've heard that .asmx files are better than .aspx files because they don't go through the whole page lifecycle. However, I don't really understand how to get a .asmx file running, and can you even call it with a POST, ie, www.mysite.com/webservice.asmx? I know I can make it work with a .aspx file, but I wanted to check to see if there was a better way before I undertake this endeavor.
Thanks for your insight!
While any extension can be mapped to any handler in ASP.NET, by default .aspx is mapped to page handler and .asmx is mapped to Web service handler. I think you are looking for .ashx which represents a generic simple handler. You just need to implement ProcessRequest method of the IHttpHandler interface after adding one to your project (Add New Item -> Generic Handler).
The .ashx works well if you want to manually process the request. Only if you want to provide a Web service (e.g. SOAP), you should go with .asmx. As a consequence, the best solution depends on the format of the HTTP POST request they send. If they send raw data in POST with their own specific protocol, go with .ashx. Otherwise, if they are using a standard RPC (SOAP, XML-RPC, ...) protocol, .asmx is probably better.
Create an .asmx file with Visual Studio. It should create a template with a HelloWorld method. Browse to it with your favorite browser and you'll actually get an explanation on how to post requests to it using various methods.
There is another type you haven't mentioned: ashx. However, in your case, a webservice (asmx) would make sense.

What is the difference between HttpHandler and a Web User Control and when to use each one?

I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong
Unfortunately your question is a little like "Should I use a sandwich or a cement mixer". HttpHandlers and User controls are completely different things.
HttpHandlers are used to process HTTP requests. For example, if you wanted to dynamically create an RSS feed, you could write an HTTP handler that handles all requests for ".rss" files, creates the output and sends it back to the user.
User controls are used within ASPX pages to encapsulate units of functionality that you want to re-use accross many pages.
Chances are, if you're using user controls successfully, you don't want to use HttpHandlers!
Basically a user control is a piece of server logic and UI. An HTTP Handler is only a piece of logic that is executed when a resource on your server is requested. For example you may decide to handle requests for images sent to your server through your own handler and serve images from a database instead of the file system. However, in this case there's no interface that the user sees and when he visits a URL on your server he would get the response you constructed in your own handler. Handlers are usually done for specific extensions and HTTP request types (POST, GET). Here's some more info on MSDN: http://msdn.microsoft.com/en-us/library/ms227675(VS.80).aspx
Expect a better answer (probably before I finish typing this) but as a quick summary.
A user control is something that can be added to a page.
A HttpHandler can be used instead of a page.
Just to clarify the question. I was reading the Hanselman post
http://www.hanselman.com/blog/CompositingTwoImagesIntoOneFromTheASPNETServerSide.aspx
and thinking that I would never solved the problem with a HttpHandler, maybe with a simple page returning a binary content.
This led me to think that I should add HttpHandler to my developer tool belt.
Even an Asp.Net page is an HttpHandler.
public class Page : TemplateControl, IHttpHandler
A user control actually resides within the asp.net aspx page.

Resources