asp.net-mvc - 从服务器导入 LESS

标签 asp.net-mvc less dotless

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

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

既然 DotLess 只会导入带有 .less 或 .css 扩展名的文件,那么推荐的方法是什么?

最佳答案

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

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

请注意,这是原型(prototype)代码:

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

关于asp.net-mvc - 从服务器导入 LESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11128824/

相关文章:

c# - 带有报表查看器的 ASp.net MVC?

css - Less 变量被下一个文件覆盖

asp.net-mvc - 为什么 LESS 文件必须设置为 Build Action "Content"才能部署到 Azure?

c# - Dotless - 无法使用 MVC Bundling 在单独的文件中引用更少的变量

css - 如果我使用 dotless,我需要 less.js 吗?

css - 如何设置 ASP.NET MVC 5 使用 dotless/LESS

asp.net-mvc - 使用 ControllerActionInvoker 进行单元测试以调用带有参数的操作

javascript - 如何在鼠标悬停在 MVC 中的链接上时在链接页面的小弹出窗口中显示实时预览?

c# - 我的 ASP.NET MVC 应用程序中的 Quartz Scheduler 仅在 IIS 服务器上刷新网页/应用程序后才执行作业

css - 如何在 less 中创建列表输出?