拦截.NET MVC3中当前ActionResult的输出流,可以通过以下方法实现:
自定义一个继承自ActionFilterAttribute的类,并重写OnActionExecuted方法,在该方法中可以获取到当前的ActionResult,并对其进行处理。
public class CustomActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var result = filterContext.Result as ContentResult;
if (result != null)
{
// 处理输出流
result.Content = "Hello World!";
}
}
}
在需要拦截输出流的Controller或Action上应用自定义的ActionFilterAttribute。
[CustomActionFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return Content("This is the original content.");
}
}
通过创建一个HttpModule,可以在Response的输出流中拦截并处理数据。
public class CustomHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
private void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var response = application.Response;
var filter = new MemoryStream();
var sw = new StreamWriter(filter);
var tw = new HtmlTextWriter(sw);
response.Filter = filter;
var original = response.Output;
response.Output = tw;
response.Flush();
response.Output.Flush();
filter.Position = 0;
var reader = new StreamReader(filter);
var html = reader.ReadToEnd();
// 处理输出流
response.Output.Write(html);
response.Output.Flush();
}
public void Dispose()
{
}
}
<modules>
<add name="CustomHttpModule" type="YourNamespace.CustomHttpModule, YourAssemblyName"/>
</modules>
</system.webServer>
通过以上方法,可以实现拦截.NET MVC3中当前ActionResult的输出流,并对其进行处理。
领取专属 10元无门槛券
手把手带您无忧上云