开发者

Intercepting HTTP in ASP.Net MVC 2

Does anyone have any idea how I can intercept the HTML of a page and stop it getting rendered back to the client?

I've tried the following, in a controller method:

var writer = new StringWriter();
var response = new HttpResponse(writer);
var context = new HttpContext(existingContext.Request, response) { User = existingContext.User };            
System.Web.HttpContext.Current = context;

//The method controller method returning an ActionResult for the page I want to render
var ViewResult = ControllerMethod();
ViewResult.ExecuteResult(this.ControllerContext);
string html = writer.ToString();

I think that at this point, the html string should have the HTML of the page that would have been rendered. As it stands, the html variable is an empty string. I suspect that this is because setting the System.Web.HttpContext.Current doesn't affect the cont开发者_如何转开发roller's HTTP context. Is this a likely cause, and if so is there an approved way of setting the context given that the property is readonly?

I'm trying to render a page to PDF by capturing the raw HTML being created and passing it to a third party component. The controller action containing the above code will then take the raw HTML and convert it to PDF, then return that.


Use the following to render a view to a string - which can then be passed to your PDF generator

string RenderViewToString(string viewName, object model, string masterName)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, masterName);

            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);

            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜