我需要获取控制器/操作的HTML标记才能生成PDF。我所做的是:
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();
}
考虑到上述情况,在SuperComplex会话中,我应该有Session [“Message”]。但由于一些奇怪的原因,它不会去那里。
我已经检查过Session.SessionId - 在两种情况下它都是相同的。
此外,在第二次或第三次请求时,请求超时!
再次:http://localhost:7401/(S(SESSION_ID))/Home/About
如果在其他浏览器中请求:会话劫持确实发生 - 但WebRequest死了! :(
帮助 - 有人吗?
答案 0 :(得分:2)
将HTML存储在Partial View中,然后使用Helper函数将其解析为字符串。
// 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();
}
}