Andre Pena
Andre Pena

Reputation: 59336

Cannot route static files in ASP.NET WebForms

We have legacy code to maintain and, to solve a specific customer customization problem, we want to route calls to some files to other files. That is, when the app calls a particular ASPX, it will end up hitting another ASPX.

If you call:

www.foo.com/admin/admin.aspx

It will actually hit:

www.foo.com/customizations/customer1/admin/admin.aspx

This is not a good design but this is legacy code. We just want to solve this.

We are using the System.Web.Routing framework to solve it. This works fine when you set RouteExistingFiles to true, except for static files (CSS, JavaScript and Images). When I first tried it, it retrieved this error:

There is no build provider register for the extension '.css'.

So I did register a build provider in the web.config file for the .css extension. I used this build provider: PageBuilderProvider because someone recommended it in the internet.

It works! But the CSS is being served with text\html content type.

How do I achieve this?

TL;DR: I want to use routes in ASP.NET Web Forms to make a call for a specific CSS file to actually retrieve another one. A customer needs this for customization.

Upvotes: 1

Views: 1074

Answers (1)

Chris Cannon
Chris Cannon

Reputation: 1167

Try coding a HttpHandler. I had to do something similar but for PDF files, I coded a custom HttpHandler in the end - works very well. You can even set the content type in the HttpHandler code and have a pattern matched path the handler will be used for in the web.config. You can also configure it in web.config not to execute if the path does not point to an existing file e.g. so a 404 is returned without having to code that in the handler itself. I can't post my code (VB.NET) ATM because I'm using a tablet but google search for tutorials. You will also probably need to use the TransmitFile function to actually write out the css file. Is it a web forms project or web site? If its a web site there is a special way of registering the HttpHandler in the web.config.

Upvotes: 1

Related Questions