Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i isolate Razor Views?

Is there a way to expose Razor syntax and (custom) helpers to people , but say ... not allow them to create code blocks or , to only limit them in the usage of the helpers and to not give them the power to execute pure C# code in the views ?

Any ideas and pointers to similar solutions are welcome !

update:// I would like to give the users the power to write their own HTML and access only to a list of html helpers. Mostly the default ones and the ones i create.

For example i do not want them to be able to execute code within @{ //code } blocks and Also no using and @model ( not sure about this one) only have access to @Html.* @if else for foreach

or better yet , give them access only to specific namespaces (this just a thought tho)

update:// After some testing , i found out that RazorEngine does as close as to what i'm trying to do : run the views in isolated environment and add access to specific namespaces.

like image 852
Nikola Sivkov Avatar asked Feb 23 '13 15:02

Nikola Sivkov


2 Answers

I would not recommend you doing that. There simply is not an easy and reliable way to give them this ability without compromising the security of your site. If you trust your users then you could do it. If you don't then a templating engine such as DotLiquid is something far more appropriate for this purpose.

like image 158
Darin Dimitrov Avatar answered Sep 18 '22 11:09

Darin Dimitrov


There is a project called RazorEngine, built upon Microsoft's Razor, that allows you to parse that syntax without being in the context of returning an MVC view. Here's how it's used:

 string template = "Hello @Model.Name! Welcome to Razor!";
 string result = Razor.Parse(template, new { Name = "World" });

You can also specify a customized template base, which should allow you to define only the Html Helpers you want to expose to your users:

 Razor.SetTemplateBase(typeof(HtmlTemplateBase<>));

 string template = 
  @"<html>
      <head>
        <title>Hello @Model.Name</title>
      </head>
      <body>
        Email: @Html.TextBoxFor(m => m.Email)
      </body>
    </html>";

  var model = new PageModel { Name = "World", Email = "[email protected]" };
  string result = Razor.Parse(template, model);
like image 34
Felipe Castro Avatar answered Sep 19 '22 11:09

Felipe Castro