Can .NET intercept and change css files?

前端 未结 7 467
渐次进展
渐次进展 2021-01-11 11:42

UPDATE 1:

I have now setup IIS6 so .NET can handle calls to .css files. What do I have to do now to get it to change css files based on the referal

7条回答
  •  囚心锁ツ
    2021-01-11 12:20

    1. In IIS, Setup the HttpHandler to receive all the file types you want (says you have done this)
    2. user Server.MapPath() on HttpRequest.Url.AbsolutePath to get the physical path
    3. Modify the path according to the domain
    4. Write the file to the response stream.

    Here is a handler (simplified) that I use routinely to server alternate files for different domains:

    using System;
    using System.IO;
    using System.Web;
    public class MultiDomainFileHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string filePath = GetDomainSpecificFilePath(context.Request.Url.Host,
                context.Server.MapPath(context.Request.Url.AbsolutePath));
    
            if (File.Exists(filePath))
            {
                switch (Path.GetExtension(filePath).ToLower())
                {
                    case ".css": context.Response.ContentType = "text/css"; break;
                    case ".jpg":
                    case ".jpeg": context.Response.ContentType = "image/jpeg"; break;
                    //other types you want to handle
                    default: context.Request.ContentType = "application/octet-stream"; break;
                }
                context.Response.WriteFile(filePath); //Write the file to response
            }
            else context.Response.StatusCode = 404;
        }
    
        private string GetDomainSpecificFilePath(string domain, string originalPath)
        {
            string prefix = "";
            switch (domain.ToLower())
            {
                case "intranetv2": prefix = FILE_PREFIX_INTRANETV2; break;
                case "www.example.com": prefix = FILE_PREFIX_EXAMPLE_DOT_COM; break;
                //other domains you want to handle
            }
            string dir = Path.GetDirectoryName(originalPath);
            string fileName = prefix + Path.GetFileName(originalPath);
            return Path.Combine(dir, fileName);
        }
    
        const string FILE_PREFIX_INTRANETV2 = "v2.", FILE_PREFIX_EXAMPLE_DOT_COM = "ex.com.";
        public bool IsReusable { get { return false; } }
    }
    

    Now, you simple need to have alternate files in the same directories. E.g:

    /Images/logo.jpg

    /Images/v2.logo.jpg

    /Styles/mystyle.css

    /Styles/v2.mystyle.css

    I hope this helps :)

提交回复
热议问题