2012-06-20 5 views
3

내 ASP.NET MVC 응용 프로그램에서 덜 변수를 반환하는 작업이 있습니다.서버에서 가져 오기 LESS

이 변수를 내 기본 LESS 파일로 가져오고 싶습니다.

DotLess는 .less 또는 .css 확장명의 파일 만 가져 오기 때문에이 작업을 수행하는 데 권장되는 방법은 무엇입니까?

답변

4

가장 쉬운 해결책은 IFileReader을 구현하는 것이 었습니다.

아래의 구현은 "~/assets"이 접두어로 붙은 모든 덜 경로에 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); 
을이 프로토 타입의 코드입니다

관련 문제