在静态页中,js和css使用虚拟路径指向网站根目录

第一步:修改web.config
<configuration>
    <system.webServer>
    <handlers>
        <add name="x" verb="GET" path="*.css.ashx" type="FileResolver" />
        <add name="xx" verb="GET" path="*.js.ashx" type="FileResolver" />
        </handlers>
    </system.webServer>
</configuration>

第二步:添加以下代码:

using System;
using System.IO;
using System.Web;

public class FileResolver : IHttpHandler {
#pragma warning disable
    private struct FileCacheItem {
        public FileCacheItem(string content) {
            Content = content;
        }
        public string Content { get; }
        public DateTime DateEntered { get; } = DateTime.Now;
    }
#pragma warning restore
    private FileCacheItem UpdateFileCache(HttpContext context, string path) {
        using var f = new FileStream(path, FileMode.Open, FileAccess.Read);
        using var r = new StreamReader(f);
        var content = r.ReadToEnd();
        r.Close();
        f.Close();
        var root = HttpRuntime.AppDomainAppVirtualPath;
        if (!root.EndsWith("/")) {
            root += "/";
        }
        content = content.Replace("~/", root);
        FileCacheItem item = new(content);
        context.Cache.Insert(path, item, new(path));
        return item;
    }
    public void ProcessRequest(HttpContext context) {
        var path = context.Request.PhysicalPath.Replace(".ashx", "");
        if (path.Contains("~\\")) {
            path = path.Replace("~", "").Replace("\\\\", "\\");
        }
        var res = context.Response;
        if (!File.Exists(path)) {
            res.StatusCode = 404;
            return;
        }
        context.Cache.Get(path);
        res.ContentType = "text/" + GetContentType(Path.GetExtension(path));
        var cache = (FileCacheItem)(context.Cache[path] ?? UpdateFileCache(context, path));
        res.Write(cache.Content);
        res.End();
    }

    private string GetContentType(string ext) => ext.ToLower() switch {
        ".css" => "css",
        ".xml" => "xml",
        ".js" => "javascript",
        _ => "plain",
    };

    public bool IsReusable => true;
}

第三步:添加以下代码

<script src="~/Scripts/jquery-1.8.0.min.js.ashx"></script>

转自:Using the FileResolver to allow virtual application paths ( ~ ) in any file - CodeProject

posted @ 2024-04-03 12:20  大胡子毛绒老头  阅读(32)  评论(0编辑  收藏  举报