在我的 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/