In ASP.NET, how to get the browser to download string content into a file? (C#)

前端 未结 6 423
情书的邮戳
情书的邮戳 2021-01-13 06:27

I would like to create a text file for export/download, like a *.csv, from an ASP.NET application. I know about Response.TransmitFile, but I want to do this without creating

6条回答
  •  一向
    一向 (楼主)
    2021-01-13 06:53

    You'll want to look at writing a Custom HTTP Handler (a class that implements IHttpHandler) and simply register it in web.config. See this article on MSDN for a good example of how to set one up.

    Here's a basic example of how you might go about implementing one to return the markup for some CSV data.

    using System.Web;
    
    public class MyCsvDocumentHandler : IHttpHandler
    {
        public static string Data
        {
            get;
            set;
        }
    
        public MyCsvDocumentHandler()
        {
        }
    
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/csv"; // Set the MIME type.
            context.Response.Write(Data); // Write the CSV data to the respone stream.
        }
    
        public bool IsReusable
        {
            // To enable pooling, return true here.
            // This keeps the handler in memory.
            get { return false; }
        }
    }
    

    This alternative, which is possibly slightly simpler, is to use an ASHX handler page. The code would be almost identical.

提交回复
热议问题