从导入服务器LESS [英] Import LESS from server

查看:187
本文介绍了从导入服务器LESS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

推荐答案

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

I found the easiest solution was to implement IFileReader.

下面的实施,使得HTTP请求与〜/资产pfixed任何减少路径$ P $,否则我们使用默认的的FileReader

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

请注意,这是原型code:

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

这篇关于从导入服务器LESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆