导入从服务器LESS(Import LESS from server)

2019-06-25 15:27发布

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

我想这些变量导入到我少主文件。

什么是这样做的,因为带点只能与.LESS或扩展名为.css文件导入建议的方法?

Answer 1:

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

下面的实现使得HTTP请求与“〜/资产”为前缀的任何LESS路径,否则我们使用默认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);


文章来源: Import LESS from server