【问题标题】:How to render an asp.net WebForm page from Global.asax?如何从 Global.asax 呈现 asp.net WebForm 页面?
【发布时间】:2010-12-04 04:18:08
【问题描述】:

出于某种原因,我玩弄“简约”的 ASP.Net 只是为了好玩。我已经禁用了很多东西,并试图重新实现一些东西。我不太明白的一件事是如何呈现 ASP.Net 页面(aspx)。

这是我目前的进展:

//global.asax
    protected virtual void Application_BeginRequest (Object sender, EventArgs e)
    {
        HtmlTextWriter writer=new HtmlTextWriter(Response.Output);
        if(Request.Url.AbsolutePath.Substring(0,Math.Min(Request.Url.AbsolutePath.Length,8))=="/static/"){
            return; //let it just serve the static files
        }else if(Request.Url.AbsolutePath=="/test1"){
            test1 o=new test1();
            o.ProcessRequest(Context);
            o.RenderControl(writer);
            writer.Flush();
            writer.Close();
            Response.Flush();
        //  Response.Write(writer.ToString());

        }else{
            Response.ContentType="text/plain";
            Response.Write("Hi world!");
        }
        CompleteRequest();
    }

/static/ 位与“hi world”一样工作。我无法让/test1 路线工作。它达到了这一点,但所显示的只是一个黑页。

我有一个包含此设计器内容的 test1.aspx 页面:

<%@ Page Language="C#" Inherits="namespace.test1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>test1</title>
</head>
<body>
    <form id="form1"> <!--just testing if two forms works and such-->

    </form>
    <form id="form2">
    <input type="text" id="test1" />
    </form>
</body>
</html>

它几乎没有代码(只是一个无关紧要的空函数)

我在这里做错了什么?

【问题讨论】:

    标签: c# asp.net webforms global-asax


    【解决方案1】:

    Global.asax 是一个红鲱鱼。 ASP.NET 正在成功呈现您请求的页面:

    test1 o=new test1();
    

    test1test1.aspx 页面的代码隐藏类。但这不是你想要的,明白吗?您希望看到的所有内容都来自 test1.aspx 文件。您需要做的是告诉 ASP.NET 将 test1.aspx 呈现到 Response.Output:

    using (var o = (Page) BuildManager.CreateInstanceFromVirtualPath("/test1.aspx", typeof (Page))) {
        o.ProcessRequest(Context);
    }
    

    【讨论】:

      【解决方案2】:

      您可以在此处使用HttpContext.Current.Server.Execute。见HttpServerUtility.Execute

      【讨论】:

        【解决方案3】:

        我的第一个想法是你不要调用隐藏的Page.FrameworkInitialize。在这种情况下,我不确定它是否真的能为你做任何事情。

        我也相信Page.ProcessRequest 会直接渲染到提供的HttpContext。请参阅 Reflector 中的 ProcessRequestMain,在 Render 期间它会调用 this.RenderControl(this.CreateHtmlTextWriter(this.Response.Output))

        我们看不到您从哪里获得请求和响应对象。您是否检查了作为 sender 参数发送给您的 HttpApplication,因此您确定您使用的是正确的对象?

        【讨论】:

        • 是的,它们是正确的 Request 和 Response 对象,它们就像内置在 global.asax 类中
        【解决方案4】:

        本文显示how to render a UserControl from a web service。可能会有所帮助。

        【讨论】:

          猜你喜欢
          • 2011-03-21
          • 1970-01-01
          • 2012-03-22
          • 1970-01-01
          • 2013-05-18
          • 2023-04-09
          • 1970-01-01
          • 2013-02-04
          • 1970-01-01
          相关资源
          最近更新 更多