开发者

How to append custom HTML to the end of view with attributes in ASP.NET MVC?

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.H开发者_如何学GottpContext.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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜