Using a custom URL rewriter, IIS6, and urls with .htm, .html, etc - c#

I have a custom site I'm building with automatic url rewriting using a custom engine. The rewriting works fine as long as the page url doesn't end in somehting like .htm or .html. For these pages it goes directly to the iis 404 page instead of hitting my rewriting engine first.
I have the * wildcard handler in the "Home Directory" section of the IIS6 configuration of that website but these urls seem to be ignored by it (altho things like css, jpg, js, etc to get sent to the url handler in my web project). How do i set up IIS6 to force these urls to get sent to the handler, while still serving the page if it exists normally?
The handler basically does this
if (!File.Exists(Request.Path))
{
doMyRewriting();
}
I have to assume that using a block like this (just and example, the real one does some other stuff to format the Request.Path to be proper with everything) should run the "doMyRewriting()" if the requested file does not exist otherwise it will serve the page normally. Am I mistaken?
If I tell IIS specifically to send .htm and .html pages thru to the .NET handler the rewriting works but if the page is actually there it will not serve it.
Any help would be greatly appreciated.
Thanks in advance!

Don't know if you can or would want to do this, but there is the Ionics Isapi url rewriter you can use.
http://www.codeplex.com/IIRF
Basically install that then set a rule to remove the .html that way it hits your rewrite engine. I use it on IIS 6 with several of my blogs.

I think if you are having IIS send all requests to .NET and your handler, then your handler will need to detect if the page exists and serve it instead of rewriting.
UrlRewriting.NET has an option to do this - you might want to look at their code to see how they're handling this case.

In my opinion, rewriting URLs with IIS 6 is best handled with an ISAPI filter written as unmanaged native code. Otherwise, you run into the issues you've mentioned - having to map all extensions to ASP.Net and losing the ability for simple file handling. With an ISAPI filter, you can choose to not rewrite some URLs and let IIS handle them as normal.
To get started, I suggest reading the ISAPI Filter Overview on MSDN.
If your filter absolutely needs the .Net framework runtime, it is possible to write a small ISAPI filter shell that hosts the CLR and forwards the requests to some managed code. The Filter.Net Framework takes this approach and may be suitable for your needs. There is the small drawback to this approach in that you will have to use the same .Net version as any ASP.Net applications that are run in the main IIS process.

Related

Is there a way to have IIS default document (default.asp) take precedence over .Net routing?

I am trying to migrate a site from classic ASP to .Net (using WebMatrix). I am planning on mixing the new .cshmtl pages in with the legacy .asp files and slowly migrate the site over time. To date, I have individual .asp pages for each piece of content (each url). As I move to .Net, the content will be coming from a database, so there will not be specific pages for each url. I love the power of routing that is available in .Net and it works well and plays nicely with the classic ASP with one exception so far.
My example is that I have an ASP page located at /crafts/default.asp and currently reference that everywhere as just /crafts/. The IIS default document setting takes care of serving the default.asp page when i just reference /crafts/. I want to start to post new items into this area of the site but run as .Net pages. so I created a /crafts.cshtml page which is designed to handle different urls and go to the database and lookup the item and display the info. So as an example I have legacy page at /crafts/fall-crafts.asp and this works fine - because there is an .asp page sitting there named that. But when i reference /crafts/ .Net takes over and serves the /crafts.cshtml page instead of serving the /crafts/default.asp file. Is there something I can do to keep the power of .Net routing in place, but still have IIS serve the default document in this case?
Modify your RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("crafts/");
...
See RouteCollection.Ignore for documentation.
Similar question (mentions some other possibly needed workarounds): Ignore folder in ASP .NET MVC
The default "routing" built into the Web Pages framework relies on matching incoming URLs to physical files on disk, looking first for the existence of cshtml or vbhtml files. All the time you have a crafts.cshtml file at the same level as a folder called crafts, the file will be served first. The solution is to remove or rename you crafts.cshtml file, but currently that will mess up your URLs.
There is a package which offers greater management over routing in Web Pages applications. It's called Routing For WebPages. It allows you to route URLs to any file name you like. You can download that via the Package Manager or Nuget and read this article that I put together that explains how to use it: http://www.mikesdotnetting.com/Article/187/More-Flexible-Routing-For-ASP.NET-Web-Pages.

Restfull urls for ASP.NET page on IIS

Ok I had a huge Issue giving this a proper title, my excuses for that.
Anyways I have started slowly to look at Web and ASP.NET again, I am a C# developer but I have mostly worked with Windows applications the past 5 years or so, It is not that I haven't touched the web as such in that time, but this is as web services (Restfull as well as the ugly SOAP services) I have also worked with more "raw" web requests.
But I have not worked with IIS or ASP.NET in all that time.
What I would like to do is hos a web page that uses a URL style I could best describe with "like rest", hence the "Restfull urls" title. Because I think most people thinks of such URL's in terms of:
http://example.com/item/
http://example.com/item/23/
and so forth. Not that they have to look like that, however I would like to use such URL's instead of
http://example.com/item?id=23
I know subtext does this, but i have not had any luck finding it in their code base.
Now as far as I can tell I could just implement some IHttpHandler's, but at least for the examples I have seen of that, they write the page source back in code, and I still have master pages etc. I wish to use instead of taking over all that stuff my self, I really just kinda wants to route http://example.com/item/23/ to http://example.com/item and asking for the item with id 23...
I hope this makes sense at all >.<... And that someone has some better examples at hand that what I have been able to find.
You can achieve this using Routing here is a link to an MSDN blog, The .Net Endpoint - Using Routes to Compose WCF WebHttp Services that should get you started.
If you're looking at asp.net/IIS, another option to look at is ASP.Net MVC. It's pretty straight forward to create RESTful services.
Here's a tutorial:
http://www.codeproject.com/Articles/233572/Build-truly-RESTful-API-and-website-using-same-ASP
So here are your options-
For .net 3.5 sp1 framework with IIS7 you can use asp.net routing feature to have MVC style urls that you mentioned should create a custom route handler implementing IRouteHandler interface as explained here How to: Use Routing with Web Forms and register your route rules in Application_Start method in Global.asax. For your example you can register a route like this
routes.Add("ItemRoute", new Route
(
"item/{itemId}",
new CustomRouteHandler("~/item.aspx")
));
and then you can access itemId in your routed item.aspx page by checking request context item
requestContext.HttpContext.Items["itemId"]
For .net framework 4 MVC you dont have to create a custom handler, you can directly use
routes.MapPageRoute("ItemRoute", "item/{itemId}", "~/item.aspx");
in you global.asax Application_Start method.
This link explains more about the Routing
A way of achieve this is using URL rewriting.
If you're planning to host your Web application in Internet Information Services 7.x, you can take advantage of IIS URL Rewriting Module:
http://www.iis.net/download/urlrewrite
URL rewriting is just mapping a friendly URL to an unfriendly, common one, which is programming-friendly to inspect GET parameters.
For example:
http://yourdomain.com/item/48 => http://yourdomain.com/Items.aspx?Id=48

Getting text after URL in asp.net / URL Rewriting (sort of!)

My app is a very simple "one page" type app-
It has Default.aspx
I'm basically trying to get, for example:
www.myappurl.com/this is my text
I want to get hold of "this is my text" from the above example.
This will be displayed on the page (for now)
I didn't really want to have to use any complext url rewriting things for this...
(My hosting provider uses IIS6)
I tried using a 404 handler, but this is a bit long winded, and i'm using shared hosting, that can't set the "execute url" on custom 404 pages.
Any other ideas?
You can add a mapping for all requests with the * extension to the ASP.NET isapi dll (GET/POST) verbs. You will need to uncheck the "verify file is on disk" checkbox when mapping the extension in IIS. (In IIS7 integrated mode, you map the extension in the web.config as well). Note that this will caause everything to be served by asp.net, even images and script files, which can slow things down.
Then create a handler mapping in your web.config to a http handler you create.
From there, in the ProcessRequest() method of the handler, you have access to the HttpContext that spawned the request and can manipulate the URL from there.
That is the easiest option, you could also create a HttpModule, or have the default page at root redirect to http://www.domain.com/default.aspx/this is my text, in the code-behind of default.aspx, you will be able to get the text following the page and slash.

POSTing to a re-written URL on IIS 6 doesn't work

I am working on a site which is programmed in C# .net. It uses a CMS called ADX Studio (a decision which predates my time there) which provides a shonky form of URL Rewriting (as far as I can tell it works by assigning an aspx page as the default 404 handler in IIS).
I have an web form which lives at a rewritten URL. I edited it so that the html form's action points back to the rewritten URL:
var u = new Uri(Request.RawUrl.Split(new char[1] { ';' }).Last());
userAdminForm.Action = u.PathAndQuery;
(kind of ugly but works based on what Request.RawUrl is on these rewritten URLs).
The "pretty" URL is something like this:
http://www.site.com/admin/user/edit/
On my development box (Windows XP/ IIS 5) when I initially tried POSTing back to URLs like this I got a HTTP 405 error. I worked around this by adding a script mapping so Aspnet_isapi.dll handles all (*) requests. And everything works fine on my development machine.
I just pushed my changes to the live server (Windows Server 2003 R2 and IIS 6) and the post fails silently. The page refreshes but all of my logic (from within an IsPostBack path in the code) doesn't get hit. No errors are displayed, it just doesn't work.
If I remove my code setting the .Action of the form then the postback works but it is posting to the ugly URL corresponding to the physical location of the aspx file rather than my page.
Am I missing a simple way to make this work? I don't want to be switching URL rewriting method or anything as this is a large legacy site and is unfortunately pretty dependent on ADX Studio so I don't want to do anything that will break that.
[edited because somehow the code above lost its code highlighting]
The issue is that the page's <form> tag is referencing the "ugly" url as the action. You can resolve that by completely removing the action tag from the form. Browsers will, by default, postback to the same page, ie. the "pretty" url.
This article explains how to accomplish an "actionless" form (~ two thirds of the way down) http://msdn.microsoft.com/en-us/library/ms972974.aspx
It seems like the problem is the same as it was on IIS 5. I can get it to work by doing the following in the IIS Manager:
Right click on the relevant website and select "Properties"
Choose the "Home Directory" tab
Click "Configuration" down in the "Application settings"
Click "Insert" next to the "Wildcard application maps"
Browse to the location of aspnet_isapi.dll (in my case: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll )
Untick "Check that file exists"
Click "OK" back through the Russian doll of dialogs.
This is basically the same as the approach that I linked to in the question for IIS5. However, it's not optimal because IIS is running every request through asp (even static files). Which seems like it can only slow things down. I'd like to be able to specify that asp only needs invoking for HTTP POST requests at least.
The weird thing is that IIS5 gave a HTTP 405 error when POSTing to an extension without a registered ISAPI extension but IIS6 just fails silently. And the page is being run through IIS (I can debug with a breakpoint in the Page_Load function) but IsPostBack (and IsCrossPagePostBack) don't get correctly set. Could it be related to the view state? Is there any alternative to my solution described above?
I've come to what I think is an optimal solution for this problem. It turns out that ADXStudio CMS does use the default 404 rule to do some form of URL rewriting. This has a problem with http POST:
when IIS initially executes a custom
URL on a 404 error, it changes POST to
GET, even if the client does a POST
request.
(thanks to elite brains' blog post about setting up IIS6 and ASP.NET MVC).
Rather than creating my own HttpModule I decided instead to use Ionics Isapi Rewrite Filter to rewrite my URLs. I then set the 404 error handler in IIS to the default. And I created this IIRF.ini file to redirect all requests to the same format as the 404 handler produced:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /Default.aspx?404;http://%{HTTP_HOST}$1 [U,L]
And everything seems to work great. The advantage over my previous answer is that the rewrite code is low level and runs fast and the -f and -d switches mean that if a file actually exists it isn't re-written and so static files don't have the overhead of running through .net.

Wildcard mapping for ASP.NET and issues with PHP

I have an application written in .NET 3.5 with C# as the language. I'm using Web Forms, but using url routing with the routes defined in my global file. Everything is working as expected. In order for the pretty paths (see: user/665 instead of user.aspx?uid=665) to work properly, I had to add a wildcard mapping in IIS5.1 (local box, not test, staging, or production) the aspnet_isapi file for the 2.0 framework. Everything works fine.
Now, my site needs a plugin for PHP. However, the PHP files are now being serviced by ASP.NET due to the wild card mapping, and hence are not processed by the PHP interpretter. Is there any way to get around this? Would I have to add some sort of handler to my web app that will take all PHP requests being handled by the ASP.NET framework and have them routed to the PHP engine? Is there an easier way? Maybe a way to exclude them in the web.config (PHP files) and have them served by the proper PHP engine?
Thanks all!
-Steve
This is a solution, but is not an elegant way (IMHO):
Create a virtual directory
Have it point to the folder with the files (in this case, a PHP plugin)
Give it the proper permissions
Change the config options for the virtual directory in IIS and make sure the wildcard mapping for that directory is removed.
This works like a charm for my situation. However, is there any way to not have to deal with virtual directories?
The problem is that the PHP extension needs to be registered.
In IIS Manager right-click on Default Website -> Properties -> Home Directory -> Configuration
Under Application Mappings make sure that .php is added and is it pointing to PHP.EXE. There should be an entry like this: extension .php, executable path C:\PHP\PHP.EXE %s %s
From what I gather, the problem is that ASP.NET is attempting to route your PHP requests, so what I would do is add a StopRoutingHandler() to your routes in the global.asax. Something like this should work:
routes.Add(new Route("{resource}.php/{*pathInfo}", new StopRoutingHandler()));
Edit: Be mindful that routes are processed in order, so I would add this to the top of your routes.

Categories

Resources