ASP.NET - in Global.asax detect ASPX page request vs. other things
I have an ASP.NET application where I want to set some additional HTTP headers (related to page expiration) if the request is for a normal ASPX page. However, I don't want to add these header开发者_如何学Pythons for things like images, or AXD handlers, or static HTML pages, etc.
What is the best way to detect, inside Global.asax request begin handler, that the current request is for an ASP.NET page?
It seems wrong to me to look at the URL for "aspx" because then when they request root pages (such as myapp.com/ or myapp.com/products) it won't work. And it just seems fragile.
Thanks,
~ Justin
I would suggest you to create HTTP module for this. HTTP modules are exactly intended for such kind of tasks.
http://www.15seconds.com/Issue/020417.htm
The ASP.Net framework is already doing the work of identification of the aspx page v/s something else. Why do the same thing again? Instead leverage the identified handler and then act accordingly. If the Application_PreRequestHandlerExecute handler, the this.Context.Handler property is set by the framework. Check this property's type to match the type of the ASPX page class. Your code in the Global.asax.cs would look something like this:
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
if(this.Context.Handler is System.Web.UI.Page)
{
//Do what you need to do for aspx requests
}
}
This approach as the benefit of working in all conditions of url routing and rewriting and is definitely superior (in my opinion) than doing any kind of string comparison on the URL.
You can use HttpContext.Current.Request.CurrentExecutionFilePath and see if that ends with ".aspx".
void Application_BeginRequest(object sender, EventArgs e) {
string pathAndQuery = Request.Url.PathAndQuery.ToString();
if (pathAndQuery.Contains(".aspx"))
//etc
allthough it might be better to check with a regex instead of contains
EDIT: sorry, missed your last two lines... didn't knew that you had subdirectories
but you don't have to check for aspx files. everything what is mapped in iis to the aspnet_isapi.dll will be processed. you can do something like this:
if (!pathAndQuery.Contains(".axd")){ //etc.
For folder level cache expiration settings, you an do it at IIS. Check this out: http://www.software-architects.com/TechnicalArticles/CachinginASPNET/tabid/75/Default.aspx#iis
In .Net 4.0 and above, you can check...
HttpContext.Current.Request.CurrentExecutionFilePathExtension
which should return ".aspx"
You'll get the correct extension without any Querystring values, and even when your request is for a default page (ex "www.myhost.com/myfolder/").
If you are using routing/friendly URLs, you can use the HttpRequest.GetFriendlyUrlFileExtension()
extension method (in Microsoft.AspNet.FriendlyUrls
assembly) to get the underlying file type (e.g. ".aspx")
精彩评论