Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Mantas 1 post 72 karma points
    Oct 16, 2019 @ 13:27
    Mantas
    1

    Overtaking HTML before render

    Hello,

    I am building a website on Umbraco 8 and I need to add rel="noopener noreferrer" to every anchor that contains external url.

    After some time googling on how to do it I figured I can overtake the generated html before the rendering and add the rel attribute where required. (Source)

    To manage it I have made a class implementing ActionFilterAttribute interface:

    internal class HtmlAnchorUpdateFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var stringBuilder = new StringBuilder();
            filterContext.HttpContext.Items["output"] = filterContext.RequestContext.HttpContext.Response.Output;
            filterContext.RequestContext.HttpContext.Response.Output = new HtmlTextWriter(new StringWriter(stringBuilder));
            filterContext.HttpContext.Items["stringBuilder"] = stringBuilder;
        }
    
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var response = filterContext.HttpContext.Items["stringBuilder"].ToString();
            var output = filterContext.HttpContext.Items["output"] as StringWriter;
            output?.Write(response);
        }
    }
    

    Also, I have registered it in the global filters using IComposer:

    public class FilterComposer : IComposer
    {
        public void Compose(Composition composition)
        {
            GlobalFilters.Filters.Add(new HtmlAnchorUpdateFilter());
        }
    }
    

    Of course this does not work as I expect it. Though the Filter attribute is getting called it gets called twice on a partial view html and not the final complete html.

    So my questions are:

    1. Is there a better approach to this problem?
    2. If not, then how can I overtake the final generated html?
Please Sign in or register to post replies

Write your reply to:

Draft