Import LESS from server

早过忘川 提交于 2019-12-09 03:19:30

问题


In my ASP.NET MVC application I have an action that returns LESS variables.

I would like to import these variables into my main LESS file.

What is the recommended approach for doing this since DotLess will only import files with .less or .css extensions?


回答1:


I found the easiest solution was to implement IFileReader.

The implementation below makes a HTTP request to any LESS path prefixed with "~/assets", otherwise we use the default FileReader.

Note that this is prototype code:

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;
        }
    }
}

To register the reader, execute the following when your application starts:

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


来源:https://stackoverflow.com/questions/11128824/import-less-from-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!