问题
I am building a Razor template-parser using something like the following:
RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage());
RazorTemplateEngine engine = new RazorTemplateEngine(host);
CodeDomProvider provider = new CSharpCodeProvider();
GeneratorResults razorTemplate = engine.GenerateCode(new StringReader(template));
var cParams = new CompilerParameters();
// set params....
var result = provider.CompileAssemblyFromDom(cParams, razorTemplate.GeneratedCode);
Now I would like to analyze razorTemplate.GeneratedCode
for the usage of some classes for security reasons, e.g. when/before compiling the following:
@{ System.Threading.Tasks.Task.Run(() => while(true)); }
I would like to detect the usage of Task
and then not compile it and throw a security-exception.
Because this are Razor-templates the following should be valid:
<i>System.Threading.Tasks.Task.Run(() => while(true))</i> is evil. Render-time: @DateTime.Now
so I can not use "simple text-search" to validate the templates.
How can I do that?
I already searched the razorTemplate
-object via the debugger, but I did not find "any methods" in there...
P.S.: The complete code can be found HERE in the method CompileAsync
.
回答1:
Using your example template, when you look at the statement that corresponds to the Task
-using code (it's something like ((CodeMemberMethod)razorTemplate.GeneratedCode.Namespaces[0].Types[0].Members[1]).Statements[0]
), you'll see that it's a CodeSnippetStatement. That means that CodeDOM doesn't know anything about the structure of the statement, it's just a string.
So, if you're not willing to try to parse the code yourself (possibly using some existing compiler, like Roslyn), you can't get the information you want from CodeDOM.
Another option would be to use the compiled assembly. In it, in the TypeRef
table, are stored all types that are used in the assembly. This table is not accessible through normal reflection, but metadata reader like Mono Cecil can read it for you.
来源:https://stackoverflow.com/questions/26562708/analyze-codecompileunit-for-used-types-classes