Is there No Way to Detect Routed URL in ASP.NET? - asp.net

Is there no way to detect if the current request is being mapped via ASP.NET 4.0 URL routing?
I have an HTTP module that handles the application's BeginRequest event. I have found that this handler is called for all file types, including CSS, JS, image files, etc., and I just want to perform an action if the target file is an ASPX page.
In the case of routed pages, all the properties of the HttpRequest object reflect the requested URL, and not the ASPX page that the request is being mapped to. How can I determine if the request will be handled by an ASPX file?
Thanks for any suggestions.

Inside of the Begin Request event a Handler has not been defined for the specific URL.
So there is no way of determining what will actually end up handling that URL because IIS has yet to decide. That happens after Begin Request has been fired, that is why all file types are being called.
That's one of the reasons why Begin Request is not a good event to really execute code on that needs to target specifically .NET files. A good use for the Begin Request method is adding cookies or headers to either a request or response. Those can be tacked on without a problem no matter what ends up handling the request.
As mentioned before I would suggest a Base Class that inherits from System.Web.UI.Page that all your other pages inherit from, or create a Master page.
Now without specifically knowing what you are trying to do it's hard to give a good solution. It may be possible to test a URL to check if it'll be fired by a Route, but I don't know how and it also seems excessive when you can handle it through a base class or master page.

You can create a BasePage as a base class for all pages in the application, and handle the Page_Load event there instead of using an HTTP module.

Related

ASP.NET life cycle, PreRequestHandlerExecute Event

I am looking into identifying handler that will handle my request.
I would like to know if request is asking for static resource (that is css,js or image files).
Upon inspecting HttpContext.Request on PreRequestHandlerExecute Event i see that handler and currentHandler variables are null for static resources and for any other custom handlers or aspx pages i have handler and currentHandler variables.
My question is: Is the is good place to differ handlers that will handle request or not?
I would like not to identify handler file extension by taking it from system.web/httpHandlers, cause i would like not to use system.web/httpHandlers just system.webServer/handlers. And i don't want to use Microsoft.Web.Administration namespace cause that will make me modify configurations on all servers.
Forgot to make an update on how i resolved it. I actually do deffer native from custom handlers on PostMapRequestHandler event. If your request will be handled by native handler than handler and currentHandler vars of HttpContext.Request will be null. Also by setting runAllManagedModulesForAllRequests to false request that will be handled by native handlers want even raise PostMapRequestHandler event. Hope this helps someone.

When to use HttpHandlers and HttpModules?

When exactly to use HttpHandlers and HttpModules?
Can't I write that code in ASPX pages' code behind?
HttpModule allows you to intercept the request (before it is handled by its handler) and response generated. It can modify both request/response if needed. ASP.NET sessions, profiles, authentication etc is also implemented as HttpModule - these module inspects the request and attach necessary context (e.g. session state based on session cookie) to the request. Such functionality is difficult to achieve via aspx code behind.
HttpHandler is the one responsible for handling the request i.e. to generate HTTP response which often (but not always) means generating some html. The page class (base for aspx) is nothing but http handler (so are other end points such as asmx, ashx, axd). The raw handler (ashx) is useful when you need absolute control over response generation - it would be possible to use aspx instead but then it would unnecessarily involve all default page/control machinery (view-state, post-date, control tree etc).

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

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

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