2009-08-18 38 views
1

有谁知道可用于从ASP.NET提供任意文件(可能是动态生成的和临时的)的基类吗?提供从ASP.NET生成的文件的样板

那种界面我想会非常简单,看起来像这样的:

class FilePage : Control // I think... 
{ 
    protected Filename { get; set; } // the filename to dump out 
    protected bool Delete { get; set; } // Delete the (temporary) file when done? 
    protected string ContentType { get; Set; } // MIME type of the file 

    abstract protected void BindData();   
} 

,你会从中获得并在抽象方法,创建您需要的任何文件,设置属性并让基类处理其余的部分。

我目前的用例是我想将数据导出为SQLite数据库。


编辑:

  • Superfiualy相关this question除了我必须生成的临时文件。

回答

2

您可以创建一个“页面”作为实现IHttpHandler的类。

public abstract class FileHandler : IHttpHandler { 

    protected string Sourcename // the filename to dump out as 
    protected string Filename // the file to dump out 
    protected bool Delete  // Delete the (temporary) file when done? 
    protected string ContentType // MIME type of the file 

    abstract protected void BindData(); 

    public bool IsReusable { 
     get { return true; } 
    } 

    public void ProcessRequest(HttpContext context) { 

     BindData(); 

     context.Response.ContentType = ContentType; 
     context.Response.AddHeader(
      "content-disposition", 
      "attachment; filename=" + Filename); 
     context.Response.WriteFile(Sourcename); 

     if(Delete) File.Delete(Sourcename); 
    } 
} 

然后,你可以按照你所说的子类来添加你想要的所有功能。如果你想推动处理像'删除'属性的东西,你也可以在那里添加一些事件。

最后,您需要更新网页。配置来收听正确的URL。在<httpHandlers>部分添加:

<add verb="*" path="myUrl.aspx" type="Namespace.And.Class, Library"/> 
+1

...这基本上是编辑帖子的完美方式。谢谢! – swilliams 2009-08-19 18:07:59

1

我不知道是否有基类可以做到这一点,但您可以清除响应头,然后将内存流写入Response.OutputStream。如果您正确设置内容类型和标题,它应该提供文件。

例子:

Response.Clear() 
Response.ClearHeaders() 
Response.AddHeader("Content-Disposition", "inline;filename=temp.pdf") 
Response.ContentType = "application/pdf" 
stream.WriteTo(Response.OutputStream) 
Response.End() 
+0

对Response.End()的要求究竟是什么?如果你只是掉到函数的末尾,它是否需要或者ASP是否处理了这个问题? – BCS 2009-08-19 16:37:23

+0

我不确定是否有一个。这可能取决于您的代码在您的项目中的位置。但是如果你把Response.End()放在那里,你肯定知道没有其他东西会被发回给请求者。 – 2009-08-19 21:48:09

2

我不知道这样的任何一类,但你可以很容易地写一个。

您可以使用.aspx文件(Web窗体)或.ashx文件(请求处理程序)来处理请求。在任何一种情况下,数据的返回方式都非常相似,您可以使用HttpResponse对象中的属性和方法。在网络表单中,您可以使用Page对象的Response属性访问它,在请求处理程序中,您将获得一个HttpContext对象作为处理具有Response属性的请求的方法的参数。

ContentType属性设置为MIME类型,并添加自定义标头"Content-Disposition",其值为"attachment; filename=nameOfTheFile.ext"

有几种将数据写入响应流的方法。您可以使用Response.Write来编写文本(将根据当前响应编码进行编码),您可以使用Response.BinaryWrite编写一个字节数组,并且可以使用Response.WriteFile在服务器上写入文件的内容。

正如您所看到的,在将数据写入响应流之前,数据不一定在文件中。除非您使用某种工具创建必须输出到文件的数据,否则您可以完全在内存中创建响应。