IHttpHandler Request object and virtual directory issue
-
19-09-2019 - |
Question
I am writing a class that inherits from IHttpHandler for script and css combining. I only want to combine if the querystring has a special parameter defined. If this parameter is not defined then I want to write the contents of the file as if the handler wasn't even involved. The one problem I'm encountering is that I have a script tag on a page that refers to a script in a virtual directory but the page I am hitting is in a subdirectory of the application.
The page that the control script is being referenced from is located at http://webserver/Admin/Default.aspx. When I access the Request object in the class that implements IHttpHandler all file path properties are the following: webserver/Admin/~/SharedScripts/control.js. How do I resolve this?
Solution 2
This is the solution I came up with:
string fileContent = string.Empty;
string filePath = context.Request.PhysicalPath;
int tildeLocation = filePath.LastIndexOf("~");
string location = (tildeLocation == -1 ? filePath : context.Server.MapPath(filePath.Substring(tildeLocation, filePath.Length - tildeLocation)));
OTHER TIPS
Basically, you need the ResolveUrl
method, but you don't have a Page
, or any controls for that matter. This article explains how to do that without a Page
object at hand.