【问题标题】:Import LESS from server从服务器导入 LESS
【发布时间】:2012-06-20 22:00:41
【问题描述】:

在我的 ASP.NET MVC 应用程序中,我有一个返回 LESS 变量的操作。

我想将这些变量导入到我的主 LESS 文件中。

由于 DotLess 只会导入具有 .less 或 .css 扩展名的文件,因此推荐的方法是什么?

【问题讨论】:

    标签: asp.net-mvc less dotless


    【解决方案1】:

    我发现最简单的解决方案是实现IFileReader

    下面的实现向任何以“~/assets”为前缀的LESS路径发出HTTP请求,否则我们使用默认的FileReader

    注意这是原型代码:

    public class HttpFileReader : IFileReader
    {
        private readonly FileReader inner;
    
        public HttpFileReader(FileReader inner)
        {
            this.inner = inner;
        }
    
        public bool DoesFileExist(string fileName)
        {
            if (!fileName.StartsWith("~/assets"))
                return inner.DoesFileExist(fileName);
    
            using (var client = new CustomWebClient())
            {
                client.HeadOnly = true;
                try
                {
                    client.DownloadString(ConvertToAbsoluteUrl(fileName));
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }
    
        public byte[] GetBinaryFileContents(string fileName)
        {
            throw new NotImplementedException();
        }
    
        public string GetFileContents(string fileName)
        {
            if (!fileName.StartsWith("~/assets"))
                return inner.GetFileContents(fileName);
    
            using (var client = new CustomWebClient())
            {
                try
                {
                    var content = client.DownloadString(ConvertToAbsoluteUrl(fileName));
                    return content;
                }
                catch
                {
                    return null;
                }
            }
        }
    
        private static string ConvertToAbsoluteUrl(string virtualPath)
        {
            return new Uri(HttpContext.Current.Request.Url, 
                VirtualPathUtility.ToAbsolute(virtualPath)).AbsoluteUri;
        }
    
        private class CustomWebClient : WebClient
        {
            public bool HeadOnly { get; set; }
            protected override WebRequest GetWebRequest(Uri address)
            {
                var request = base.GetWebRequest(address);
                if (HeadOnly && request.Method == "GET")
                    request.Method = "HEAD";
    
                return request;
            }
        }
    }
    

    要注册阅读器,请在应用程序启动时执行以下操作:

    var configuration = new WebConfigConfigurationLoader().GetConfiguration();
                configuration.LessSource = typeof(HttpFileReader);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 2015-03-16
      • 2019-11-28
      • 1970-01-01
      • 2016-04-16
      相关资源
      最近更新 更多