How to add custom HTML at the end of an attribute view in ASP.NET MVC?

Suppose we have some kind of action in the controller:

public ActionResult SomeAction()
{
    return View();
}

I want to be able to add some HTML code at the end of the presentation of the HTML result using attributes, for example:

[SomeHTML]
public ActionResult SomeAction()
{
    return View();
}

Where

public class SomeHTMLAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var response = filterContext.HttpContext.Response;

        if (response.ContentType == "text/html")
        {
            response.Write("someHTML");
        }
    }
}

Filters (ActionFilterAttribute) allow you to add HTML code to the top or bottom of a web page, but not to the end of the HTML view.

How to do it?

+5
source share
1 answer

You can use the Response filter:

public class SomeHTMLAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Filter = new SomeHTMLFilter(filterContext.HttpContext.Response.Filter);
        base.OnActionExecuting(filterContext);
    }
}

public class SomeHTMLFilter : MemoryStream
{
    private readonly Stream _outputStream;
    public SomeHTMLFilter(Stream outputStream)
    {
        _outputStream = outputStream;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        _outputStream.Write(buffer, 0, buffer.Length);
    }

    public override void Close()
    {
        var buffer = Encoding.UTF8.GetBytes("Hello World");
        _outputStream.Write(buffer, 0, buffer.Length);
        base.Close();
    }
}
+12
source

All Articles