Skip to content

Instantly share code, notes, and snippets.

@g0t4
Last active August 29, 2015 13:55
Show Gist options
  • Save g0t4/8718256 to your computer and use it in GitHub Desktop.
Save g0t4/8718256 to your computer and use it in GitHub Desktop.
Razor allow custom html builders to use @ syntax and not encode the output
// Out of the box, WebViewPage essentially does this to write content:
Output.Write(HttpUtility.HtmlEncode(content));
// And HttpUtility.HtmlEncode will encode anything not marked with the IHtmlString interface
// If we have a custom html builder we have to use something like this:
@Html.Raw(safeBuilder)
// This is a lot of extra typing
// I like that it's explicit that it's Raw html but we are using a safe builder so we shouldn't need the ceremony simply because our safe builder isn't marked with IHtmlString.
// This can happen if we're using a builder from a 3rd party library and we can't change the code or if we don't want to take a dependency to IHtmlString.
// But we can work around this!
// Here's a fake html builder
public class MySafeHtmlBuilder
{
private readonly string _Html;
public MySafeHtmlBuilder(string html)
{
_Html = html;
}
public override string ToString()
{
return _Html;
}
}
// And here's using it in a view
@(new MySafeHtmlBuilder("<span>hi</span>"))
// And to make it work, setup a custom razor WebViewPage.
// The magic is in overriding Write and if your custom type is detected, to just write it to the output directly
public abstract class MyRazorPage<TModel> : WebViewPage<TModel>
{
public override void Write(object value)
{
if (value is MySafeHtmlBuilder)
{
Output.Write(value);
return;
}
base.Write(value);
}
}
// Don't forget to update your razor config in the Web.Config in your views folder
<pages pageBaseType="Namespace.MyRazorPage">
// FYI this is a POC, I haven't had much chance to use it extensively in reality, but it should suffice
// Warning: make sure you are actually producing safe html, or you'll be vulnerable to XSS attacks!
// DO NOT DO THINGS LIKE THIS!!!:
public override void Write(object value)
{
Output.Write(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment