完成您想要的一个想法是使用全局操作过滤器。这将获取操作的结果,并允许您在将它们发送回浏览器之前对其进行修改。我使用这种技术将 CSS 类添加到页面的 body 标记中,但我相信它也适用于您的应用程序。
这是我使用的代码(归结为基础):
public class GlobalCssClassFilter : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
//build the data you need for the filter here and put it into the filterContext
//ex: filterContext.HttpContext.Items.Add("key", "value");
//activate the filter, passing the HtppContext we will need in the filter.
filterContext.HttpContext.Response.Filter = new GlobalCssStream(filterContext.HttpContext);
}
}
public class GlobalCssStream : MemoryStream {
//to store the context for retrieving the area, controller, and action
private readonly HttpContextBase _context;
//to store the response for the Write override
private readonly Stream _response;
public GlobalCssStream(HttpContextBase context) {
_context = context;
_response = context.Response.Filter;
}
public override void Write(byte[] buffer, int offset, int count) {
//get the text of the page being output
var html = Encoding.UTF8.GetString(buffer);
//get the data from the context
//ex var area = _context.Items["key"] == null ? "" : _context.Items["key"].ToString();
//find your tags and add the new ones here
//modify the 'html' variable to accomplish this
//put the modified page back to the response.
buffer = Encoding.UTF8.GetBytes(html);
_response.Write(buffer, offset, buffer.Length);
}
}
需要注意的一件事是,我相信 HTML 被缓冲到 8K 块中,因此如果您的页面超过该大小,您可能必须确定如何处理它。对于我的应用程序,我不必处理这个问题。
此外,由于所有内容都是通过此过滤器发送的,因此您需要确保所做的更改不会影响 JSON 结果等内容。