there is a smooth way to open a static html string from code behind whitout writing it to a file? At the moment i'm doing something like below:
using (StreamWriter sw = new StreamWriter("\\mypath\\test.html",false))
{
sw.Write(my_html_string); //I build 'my_html_string' inside the code
}
Response.Redirect("http://mysite/mypath/test.html");
but what i'd like to do is something like:
Page.Show(my_html_string);
without wasting time writing it to a file.
Thanks,
答案 0 :(得分:1)
最原始的方法是通过IHttpHandler
。
在Visual Studio中,通过菜单:“添加”>“新项目...”>“通用处理程序”。
您最终得到一个.ashx
和一个相应的.ashx.cs
代码隐藏文件,您可以在其中编写代码。
您导航到http://yourwebite/<nameOfYourHttpHandler>.ashx
以查看呈现的html。
HttpHandler
可以是路由的一部分,也可以接受查询字符串参数。
MyHandler.ashx
<%@ WebHandler Language="C#" CodeBehind="MyHandler.ashx.cs" Class="PFX.MyHandler" %>
MyHandler.ashx.cs
using System;
using System.Web;
namespace PFX
{
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Implement logic to build your html string here.
String html = "<html><head></head><body><b>foobar</b></body></html>";
// Set any appropriate http-headers here.
context.Response.ContentType = "text/html";
context.Response.Write(html);
}
public Boolean IsReusable
{
get { return false; }
}
}
}
==按LEGION编辑==
上面的代码可以完美地工作,但是如果您需要将以前的ASPX页面的某些值传递给处理程序(如我),则需要执行以下操作:
previousPage.aspx.cs
protected void MyButton_Click(object sender, EventArgs e)
{
String my_html_string = string.empty;
//Code that build the html String
HttpContext.Current.Application["my_key_name"] = my_html_string;
Response.Redirect("~/myHandler.ashx");
}
MyHandler.ashx.cs
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write(context.Application["my_key_name"]);
}
public Boolean IsReusable
{
get { return false; }
}
}