我正在尝试以编程方式将 aspx 页面呈现为字符串。渲染将通过控制台应用程序完成。现在我已经让它与在 aspx 页面中以编程方式声明的控件一起工作,这一切都很好而且很花哨。但是静态声明的控件呢?有什么方法可以实现吗?
示例代码:页面渲染:
static string RenderPage() {
ClassLibrary1.FormlessPage pageHolder = (ClassLibrary1.FormlessPage)new WebApplication1.WebForm1();
pageHolder.DesignerInitialize();
StringWriter output = new StringWriter();
HttpRequest httpRequest = new HttpRequest("", "http://localhost/", "");
HttpResponse httpResponse = new HttpResponse(output);
HttpContext context = new HttpContext(httpRequest, httpResponse);
context.Server.Execute(pageHolder, output, false);
return output.ToString();
}
无格式页面类
namespace ClassLibrary1 {
public class FormlessPage : System.Web.UI.Page {
public override void VerifyRenderingInServerForm(Control control) {}
}
}
现在,当我在 WebForm1 中声明控件时(在引用 Web 应用程序项目中,但在同一个项目中完成时行为是相同的),它们呈现得很好。
public partial class WebForm1 : ClassLibrary1.FormlessPage {
protected void Page_Load(object sender, EventArgs e) {
this.Controls.Add(new TextBox() { ID = "tbSomeText", Text = "default text" });
}
}
...但不会呈现静态 html 和静态声明的控件。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
...blah...blah...
<form id="form1" runat="server">
<div>
text
<asp:TextBox runat="server" ID="tbSomething"></asp:TextBox>
</div>
</form>
...blah...blah...
有没有办法完全伪造这种行为并实现标记渲染?上面的渲染输出很简单:
<input name="tbSomeText" type="text" value="default text" id="tbSomeText" />