在我的 ASP.NET MVC 应用程序中,我有一个返回 LESS 变量的操作。
我想将这些变量导入到我的主 LESS 文件中。
由于 DotLess 只会导入扩展名为 .less 或 .css 的文件,因此推荐的方法是什么?
我发现最简单的解决方案是实施IFileReader
.
下面的实现向任何以“~/assets”为前缀的 LESS 路径发出 HTTP 请求,否则我们使用默认的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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)