2012-06-20 115 views
3

在我的ASP.NET MVC應用程序中,我有一個返回LESS變量的操作。從服務器導入LESS

我想將這些變量導入到我的主LESS文件中。

這樣做的建議方法是什麼?DotLess只會導入帶.less或.css擴展名的文件?

回答

4

我發現最簡單的解決方案是實施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);