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