HttpWebRequest - ASP .NET MVC 3 传递会话状态

发布于 2025-01-07 18:21:12 字数 1389 浏览 0 评论 0原文

我需要获取控制器/操作的 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 死了! :(

帮忙 - 有人吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女净妖师 2025-01-14 18:21:12

将 HTML 存储在部分视图中,然后使用 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();
    }
}

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();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文