Assume we have some action in controller:
public ActionResult SomeAction()
{
return View();
}
I want to have a possibility to append some HTML code to the end of view's HTML result with help of attributes, e.g.:
[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 to append some HTML code to the top or bottom of web-page but not to the end of view's HTML.
How to archive this?
You could use a 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With