代码之家  ›  专栏  ›  技术社区  ›  theringostarrs

HttpModule/HttpApplication测试url是否为文件请求

  •  2
  • theringostarrs  · 技术社区  · 15 年前

    在HttpModule中,我想检查url是否以文件结尾:

    以及文件扩展名是什么,即.css还是js

    4 回复  |  直到 15 年前
        1
  •  4
  •   Damien McGivern    15 年前

    下面的代码应该为您获取请求文件的扩展名。

    private void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;
    
        string ext = System.IO.Path.GetExtension(context.Request.Path);
        // ext will always start with dot
    
    }
    

    但与.aspx和.ashx等文件类型不同,您在示例中使用的.js和.css等文件类型在默认情况下不会在IIS内的ASP.Net dll中注册,因此当它们被请求时,IIS不会通过ASP.Net管道传递请求,因此不会运行HttpModule或HttpHandler。如何配置这种情况取决于您运行的IIS版本。

        2
  •  1
  •   L.Archawat    11 年前
            string url = context.Request.Path;
            string extension = VirtualPathUtility.GetExtension(url);
    
        3
  •  0
  •   John Saunders    15 年前

    请看一下 HttpRequest.Url . 它是那种类型的 System.Uri .

        4
  •  0
  •   Keltex    15 年前

    // get the URI
    Uri MyUrl = Request.Url; 
    // remove path because System.IO.Path doesn't like forward slashes
    string Filename = MyUrl.Segments[MyUrl.Segments.Length-1]; 
    // Extract the extension
    string Extension = System.IO.Path.GetExtension(Filename); 
    

    注意 Extension 将始终具有领先的“.”。e、 g.'css'或'.js'