473,804 Members | 2,008 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do use change the default http handler in ASP,NET similar to ISAPI filter ?

Answer. Use IHttpHandler.
thanks Ro ry for coming up with this code.
It processes css file to add variables. neat idea

using System;
using System.IO;
using System.Text;
using System.Text.Reg ularExpressions ;
using System.Web;
using System.Web.Cach ing;

namespace CssHandler {
public class CssHandler : IHttpHandler {

// We're going to use a constant for the name of our Cache object
variable.
//
// I think that using constants for this purpose is better than
using string
// literals.
//
// For example, which of the following would be easier to maintain:
//
// Cache["Some really long and error prone string"] = someValue;
// - or -
// Cache[SOME_CONSTANT] = someValue;
//
// I think I've made my point.
private const string CSS_CACHE_BODY = "Css.FileBo dy";

// We don't really need this constructor. It's here for decorative
purposes only -
// Kind of like the plastic grass you get with sushi.
public CssHandler() {}

// IHttpHandler method - Ignore this one. These aren't the droids
you're looking for.
public bool IsReusable { get { return false; } }

// IHttpHandler method - This is the entry point for our handler.
public void ProcessRequest( System.Web.Http Context context ) {

try {
// Grab the filename that was requested by the browser. Since this
handler is
// for CSS documents, the filename is probably going to be
something like
// "styles.css " - It could, of course, be any other CSS document
in the system.
// "styles.css " was just an example, OK? Get over it.
string file = context.Request .PhysicalPath;

// Does the file even exist? If it doesn't, then let's just forget
about the whole
// thing. We've been had. You can add your own error processing
here, such as
// returning a 404 error to the browser. I'd do it, but I'm half
dead from sleep
// deprivation in Connecticut, and it isn't really the focus of
this sample code.
if (!File.Exists(f ile))
return;

// We're going to store the process CSS file in the following
variable named "body."
//
// Notice that when we try to pull the processed CSS from the
cache, we're appending
// the file name of the stylesheet we're currently processing to
the "CSS_CACHE_BODY "
// variable. This is so that our handler can deal with multiple
stylesheets. If we didn't
// do this, then each stylesheet to be processed would overwrite
the previous one in
// the cache. So many bad things would come of this that I prefer
not to think about it.
// Hence using the file name as a qualifier to create a
unique(ish) key.

string body = string.Empty;

if (context.Cache[CSS_CACHE_BODY + file] != null)
body = context.Cache[CSS_CACHE_BODY + file].ToString();
//string body = context.Cache[CSS_CACHE_BODY + file] != null ?
// context.Cache[CSS_CACHE_BODY].ToString() : string.Empty;

// If "body" is equal to string.Empty, then it means we either
haven't processed
// the stylesheet yet, or that it's been blown out of the cache.
if (body == string.Empty) {

// Read the contents of the file into a variable named "body."
StreamReader reader = new StreamReader(fi le);
body = reader.ReadToEn d();
reader.Close();

// Strip the comments from the CSS document. If we don't, then
they'll get in the
// way later on when we perform the actual processing.
body = StripComments(b ody);

// Now that we've stripped the comments, we can go ahead and
process the CSS.
body = ProcessStyleShe et(body);

// Almost time to stuff the contents of the "body" variable into
the Cache.
//
// First, we're going to create a CacheDependency object that
we'll associate
// with our Cache item (the processed CSS body). If the CSS file
is changed at
// any time, the cached object will be vaporized, and null will
be returned in
// the "if" test you saw a few lines ago, causing this code to
run again.
//
// If you'd like a detailed explanation of the CacheDependency
object, then I
// can recommend the world's greatest CacheDependency tutorial
(which I
// happened to write): http://neopoleon.com/blog/posts/1976.aspx
//
// Note that I'm just kidding about all this "world's greatest"
crap. You have
// to find ways to make yourself feel good about sitting at home
on a Friday
// night (Saturday morning now) while putting together sample
code. It's fun
// and all, but something tells me that I should be out getting
drunk and trying
// to get it on with a sofa.
CacheDependency cd = new CacheDependency (file);

// We've performed all the processing necessary, so let's store
this stylesheet
// in the cache.
//
// Note that when using a CacheDependency , you use the "Insert"
method of the
// Cache object. I understand that some of you might not like
this, but I don't
// like mushrooms or pork, and I have to co-exist with them - we
all have to
// do our part to be tolerant of the world around us.
context.Cache.I nsert(CSS_CACHE _BODY + file, body, cd);
}

// Whether we've had to process a file or not, we have to dump its
contents to the
// Response stream. That's what we're doing here.
//
// This is the last step in the process. Once it's complete, our
handler's job
// is finished.
context.Respons e.Write(body);
} catch (Exception ex) {
context.Respons e.Write(ex.Mess age);
}
}

// This is the method that we're using (as its name implies) to
strip comments from
// the body of the CSS document.
//
// There's some regular expressions stuff in here. A discussion of
regular expressions
// is beyond the scope of this tutorial, so just pretend like you
never saw this.
private string StripComments( string body ) {
body = Regex.Replace(b ody, @"/\*.+?\*/", "",
RegexOptions.Si ngleline);
return body;
}

// This where the real work is getting done. One of our modern
"@define" stylesheets
// comes in this end, and goes out the other in a format that a
browser will understand.
private string ProcessStyleShe et( string body ) {
// I made the decision to use regular expressions to extract the
@define block
// from the rest of the CSS document.
//
// If you don't understand regular expressions, then I can
wholeheartedly
// recommend Dan Appleman's guide to .NET regular expressions. It's
short,
// available online, and to the point.
Regex regex = new Regex(@"@define \s*{(?<defines>[^}]*)}",
RegexOptions.Si ngleline);
Match match = regex.Match(bod y);

// Did our regular expression find a @define block? If not, then
let's just return
// the stylesheet unmodified. No reason to hop through the rest of
the code if
// there's nothing to do, eh?
if (!match.Success )
return body;

// The regular expression ought to have isolated the variable
name/value pairs
// in the @define block. We're going to separate these key/value
pairs out into
// a string array so that we can manipulate them individually.
string[] lines = match.Groups["defines"].Value.Split(ne w char[]
{';'});

// We're going to be performing some string manipulation on the CSS
document
// body. Like good little coders, we're NOT going to do this with a
string -
// Rather, we're going to do it with a StringBuilder.
StringBuilder sb = new StringBuilder(b ody);

// Iterate through each element of the "lines" array. Each string
in the "lines"
// array should consist of one key/value pair.
foreach (string line in lines) {

// Did we get a blank line? If so, then let's move onto the next.
if (string.Empty == line.Trim())
continue;

// The CSS assignment operator is the colon (':') - We'll split
the line on
// this character, resulting in an array with two elements. The
first
// element will be the variable name, while the second will be the
variable
// value.
string[] tokens = line.Split(new char[] {':'});
string variableName = tokens[0].Trim();
string variableValue = tokens[1].Trim();

// Now that we've extracted the variable name/value from the line,
we can
// replace all of the instances of the variable name in the rest
of the
// CSS document with the variable's value. This is where all the
"magic"
// happens.
sb.Replace("@" + variableName, variableValue);
}

// All done. Return our processed stylesheet to the caller. Not so
bad, eh?
return sb.ToString();
}

}
}
------------
<?xml version="1.0" encoding="utf-8" ?>
<configuratio n>

<system.web>

........

<!-- Pssssst - this is the stuff we have to add to the config file
to map CSS files to
the custom handler -->
<httpHandlers >
<add verb="GET" path="*.css" type="CssHandle r.CssHandler,
CssHandler" />
</httpHandlers>

</system.web>

</configuration>
Nov 18 '05 #1
0 1899

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2008
by: Chris Hughes | last post by:
I have an environment with many thousands of client machines uploading data files several times each day to a web server via HTTP PUT. To avoid disk I/O (for performance), I am implementing a HTTP handler to intercept and process incoming data without touching the disk. I cannot detect PUT requests with my handler (don't know if this is even supported), so I'm redirecting all requests to the handler as POST using an ISAPI filter. I...
1
1622
by: Jeremy | last post by:
Hi there, We recently upgraded to the 1.1 framework, and of course, all of our 1.0 asp.net apps starting using the 1.1 framework, which we didn't want to happen. I found an MS article saying if you modify the ISAPI filter setting in IIS for the site to point to the 1.0 aspnet_filter.dll, your app will then use the 1.0 framework.
2
2049
by: Norton | last post by:
I had a person tell me the other day that a person would not be able to beat the efficiency of an ISAPI dll, especially by using handlers/modules. Of course, they could only say the reason was that it is written in C++, which should have nothing to do with it. But, in general, can you write a handler that will handle just as many connections as an ISAPI dll? Isn't a handler a managed code answer to the ISAPI dll solution? Thanks.
5
1784
by: Shaun | last post by:
Hi, I'm trying to implement an http handler that will redirect requests made for specific folder which don't exists. Currently my handler gets called if i request a non existing file but if i try and request a folder, I get a 404 error. Example:
0
912
by: Matt MacDonald | last post by:
Hi all, Here is what I'm trying to accomplish. I need to secure every file in an ASP.NET 2.0 website. From what I'm reading online, I should be able to do this by registering the file extensions with the .net 2.0 ISAPI filter in IIS and add an HTTPHandler item to my web.config. The problem I'm having is that I can't seem to find a handler that will make the user log into the site and then forward them back to the document they were...
0
1657
by: Chris Curvey | last post by:
Hi all, I'm trying to write an ISAPI filter in Python, using the examples that come in the "isapi" directory of the win32com package. The installation program itself runs fine, but when I examine the properties of my web server, my filter has a big red down arrow next to it. But I can't seem to figure out where I should be looking to find the trouble. If anyone can point me to the right place (or see an obvious error in the code...
11
26648
by: cybervigilante | last post by:
I can't seem to change the include path on my local winmachine no matter what I do. It comes up as includ_path .;C:\php5\pear in phpinfo() but there is no such file. I installed the WAMP package and PEAR is in c:\wamp\php\pear I modified php.ini in the c:\wamp\php directory to reflect the actual path, but even stopping and restarting my server shows the c: \php5\pear path. I can't change it no matter what I do I also tried the...
9
5042
by: Andy Fish | last post by:
Hi, I am wondering if there is any way to log the HTTP traffic on an IIS server (including headers but preferably the body as well), either at the IIS or asp.net level I know I could write my own isapi dll or .net filter, but I was rather hoping someone else has already done it. I'm sure it's quite a common requirement
10
9026
by: Eirik Eldorsen | last post by:
How can I 301 redirect www.example.com/default.aspx to www.example.com without using ISAPI filters?
0
9711
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10088
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7633
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6862
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.