Skip to content

Instantly share code, notes, and snippets.

@DamianEdwards
Last active December 14, 2015 00:37
Show Gist options
  • Select an option

  • Save DamianEdwards/d57810d28d977058e702 to your computer and use it in GitHub Desktop.

Select an option

Save DamianEdwards/d57810d28d977058e702 to your computer and use it in GitHub Desktop.
using System.Threading.Tasks;
using Microsoft.AspNet.Razor.TagHelpers;
namespace WebApplication1.TagHelpers
{
[HtmlTargetElement("raw")]
public class RawTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = await output.GetChildContentAsync(false);
var raw = System.Net.WebUtility.HtmlDecode(childContent.GetContent());
output.Content.SetHtmlContent(raw);
}
}
}
using System;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNet.Razor.TagHelpers;
namespace WebApplication1.TagHelpers
{
[HtmlTargetElement("raw")]
public class RawTagHelper : TagHelper
{
private readonly HtmlEncoder _noOpEncoder = new NoOpEncoder();
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = await output.GetChildContentAsync(false);
// Maybe we should just make this work? It doesn't because the TagHelperContent buffer already contains
// HTML encoded content. This API looks like it should work this way, but doesn't...
var rawChildContent = childContent.GetContent(_noOpEncoder /* Maybe a null should work here too (no encoding) */);
// ...so we have to decode it here, which is less than ideal.
var raw = System.Net.WebUtility.HtmlDecode(childContent.GetContent());
output.Content.SetHtmlContent(raw);
}
private class NoOpEncoder : HtmlEncoder
{
public override int MaxOutputCharactersPerInputCharacter
{
get
{
return 10;
}
}
public override unsafe int FindFirstCharacterToEncode(char* text, int textLength)
{
return -1;
}
public override unsafe bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten)
{
numberOfCharactersWritten = 0;
return false;
}
public override bool WillEncode(int unicodeScalar)
{
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment