gpt4 book ai didi

asp.net MVC 3/4 相当于 response.filter

转载 作者:行者123 更新时间:2023-12-03 21:44:15 27 4
gpt4 key购买 nike

我需要拦截将发送到浏览器的所有 html 并替换那里的一些标签。这将需要在全局范围内针对每个 View 进行。使用 C# 在 ASP.NET MVC 3 或 4 中执行此操作的最佳方法是什么?过去,我使用 Global.asax (vb) 中的“response.filter”在 ASP.net Webforms 中完成了此操作

Private Sub Global_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRequestHandlerExecute
Response.Filter = New ReplaceTags(Response.Filter)
End Sub

这调用了我创建的一个类,该类继承自 system.io.stream 并遍历 html 以替换所有标签。
我不知道如何使用 C# 在 ASP.NET MVC 4 中做到这一点。您可能已经注意到,我是 MVC 世界中的新手。

最佳答案

您仍然可以在 ASP.NET MVC 中使用响应过滤器:

public class ReplaceTagsFilter : MemoryStream
{
private readonly Stream _response;
public ReplaceTagsFilter(Stream response)
{
_response = response;
}

public override void Write(byte[] buffer, int offset, int count)
{
var html = Encoding.UTF8.GetString(buffer);
html = ReplaceTags(html);
buffer = Encoding.UTF8.GetBytes(html);
_response.Write(buffer, offset, buffer.Length);
}

private string ReplaceTags(string html)
{
// TODO: go ahead and implement the filtering logic
throw new NotImplementedException();
}
}

然后编写一个自定义操作过滤器,它将注册响应过滤器:
public class ReplaceTagsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.HttpContext.Response;
response.Filter = new ReplaceTagsFilter(response.Filter);
}
}

现在剩下的就是装饰要应用此过滤器的 Controller /操作:
[ReplaceTags]
public ActionResult Index()
{
return View();
}

或者如果您想应用于所有操作,则将其注册为 Global.asax 中的全局操作过滤器。

关于asp.net MVC 3/4 相当于 response.filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10591651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com