Reputation: 854
I need to acquire HTML markup of a controller/action in order to generate PDF. What I have done is:
public ActionResult Index()
{
Session["Message"] = "SESSION-MESSAGE";
String URL = "http://localhost:7401/Home/SuperComplex";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
req.CookieContainer = new CookieContainer();
for (int i = 0; i <= this.Request.Cookies.Count - 1; i++)
req.CookieContainer.Add(
new System.Net.Cookie(
name: this.Request.Cookies[i].Name,
value: Request.Cookies[i].Value,
path: Request.Cookies[i].Path, domain: this.HttpContext.Request.Url.Host)
);
using (var r = req.GetResponse())
{
using (var s = new StreamReader(r.GetResponseStream()))
{
var htmlToPrint = s.ReadToEnd();
Response.Write("<h1>" + htmlToPrint + "</h1>");
}
}
return View();
}
Considering above said situation, in SuperComplex session, I should have the Session["Message"]. But for some strange reason, it does not go there.
I have checked Session.SessionId - in both cases it is same.
Also, on second or third request, request timesout!
Again: http://localhost:7401/(S(SESSION_ID))/Home/About
If requested in other browser: session hijack does happen - but WebRequest dies! :(
Help - anyone?
Upvotes: 2
Views: 3915
Reputation: 2239
Store your HTML in a Partial View and then use a Helper function to parse it into a string.
// usage
/*
* http://stackoverflow.com/questions/4344533/asp-net-mvc-razor-how-to-render-a-razor-partial-views-html-inside-the-controll
*
var model = _repository.Find(x => x.PropertyID > 3).FirstOrDefault();
var test = this.RenderViewToString("DataModel", model);
return Content(test);
*/
public static string RenderPartialToString<T>(this ControllerBase controller, string partialName, T model)
{
var vd = new ViewDataDictionary(controller.ViewData);
var vp = new ViewPage
{
ViewData = vd,
ViewContext = new ViewContext(),
Url = new UrlHelper(controller.ControllerContext.RequestContext)
};
ViewEngineResult result = ViewEngines
.Engines
.FindPartialView(controller.ControllerContext, partialName);
if (result.View == null)
{
throw new InvalidOperationException(
string.Format("The partial view '{0}' could not be found", partialName));
}
var partialPath = ((RazorView)result.View).ViewPath;
vp.ViewData.Model = model;
using(StringWriter sw = new StringWriter()) {
ViewContext viewContext = new ViewContext(controller.ControllerContext, result.View, vd, controller.TempData, sw);
result.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
Upvotes: 2