Adr*_*ore 12 css asp.net-mvc dotless
我编写了一个ASP.NET MVC操作方法,它接收.less文件名,通过它处理Less.Parse(<filename>)并输出处理过的css文件.
只要.less代码有效,这样就可以正常工作,但是如果有错误,则dotLess只返回一个空字符串.因此,如果处理文件时出错,我的action方法将返回一个空的css文件.
如何输出错误消息,而是更详细地描述语法错误?
que*_*rin 14
dotLess解析器捕获异常并将它们输出到Logger.dotLess执行此操作的源代码片段是LessEngine.TransformToCss:
public string TransformToCss(string source, string fileName)
{
try
{
Ruleset ruleset = this.Parser.Parse(source, fileName);
Env env = new Env();
env.Compress = this.Compress;
Env env2 = env;
return ruleset.ToCSS(env2);
}
catch (ParserException exception)
{
this.Logger.Error(exception.Message);
}
return "";
}
Run Code Online (Sandbox Code Playgroud)
Less.Parse有一个带有DotlessConfiguration对象的重载,它提供了几个你可以使用的属性:
public class DotlessConfiguration
{
// Properties
public bool CacheEnabled { get; set; }
public Type LessSource { get; set; }
public Type Logger { get; set; }
public LogLevel LogLevel { get; set; }
public bool MinifyOutput { get; set; }
public int Optimization { get; set; }
public bool Web { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您会注意到该Logger属性属于类型Type.无论您提供什么类型,都必须实施dotless.Core.Loggers.ILogger:
public interface ILogger
{
// Methods
void Debug(string message);
void Error(string message);
void Info(string message);
void Log(LogLevel level, string message);
void Warn(string message);
}
Run Code Online (Sandbox Code Playgroud)
正如我们在第一个片段中看到的那样,Error在解析过程中遇到错误时,将调用记录器上的方法.
现在,所有这一点的一个关键点是实现的类型的实例是如何实例ILogger化的.在内部,dotLess使用一个烘焙到DLL中的IoC容器.在方法调用之后,它似乎最终将调用Activator.CreateInstance实例化ILogger.
我希望这至少有点帮助.
我今天刚刚在RequestReduce项目中遇到过这个问题.我变得空白 - > css转换因为有解析错误似乎进入以太.感谢qes的回答,我能够找到一个解决方案,我可以将错误写入响应流.这是我的dotless.Core.Loggers.ILogger:
public class LessLogger : ILogger
{
public void Log(LogLevel level, string message)
{
}
public void Info(string message)
{
}
public void Debug(string message)
{
}
public void Warn(string message)
{
}
public void Error(string message)
{
Response.Write(message);
}
public HttpResponseBase Response { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我把它传递给发送到EngineFactory的配置:
var engine = new EngineFactory(new DotlessConfiguration
{
CacheEnabled = false,
Logger = typeof (LessLogger)
}
).GetEngine();
Run Code Online (Sandbox Code Playgroud)
对于单元测试目的,我想传入我的HttpResponseBase,它会写错误.这是我觉得事情变得丑陋与一些讨厌的演员来获取我的记录器的参考:
((LessLogger)((LessEngine)((ParameterDecorator)engine).Underlying).Logger).Response = response;
Run Code Online (Sandbox Code Playgroud)
我希望这会有所帮助,如果有人知道更优雅的方式来获取对记录器的引用,请告诉我.
您可以使用web.config轻松完成此操作.在无点配置部分中,添加以下内容:logger="dotless.Core.Loggers.AspResponseLogger".这将使无点输出错误而不是空白css.
我已经将以下内容作为示例.("..."表示web.config中的现有内容).在我的示例中,缓存设置为false.这对于调试目的很有用.在正常情况下,它应该设置为true.
<configuration>
<configSections>
...
<section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler,dotless.Core" />
</configSections>
<dotless minifyCss="false" cache="false"
logger="dotless.Core.Loggers.AspResponseLogger" />
...
</configuration>
Run Code Online (Sandbox Code Playgroud)