How to deliver big files in ASP.NET Response?

前端 未结 4 1087
慢半拍i
慢半拍i 2020-11-28 03:28

I am not looking for any alternative of streaming file contents from database, indeed I am looking for root of the problem, this was running file till IIS

4条回答
  •  情书的邮戳
    2020-11-28 03:36

    What I would do is use the not so well-known ASP.NET Response.TransmitFile method, as it's very fast (and possibly uses IIS kernel cache) and takes care of all header stuff. It is based on the Windows unmanaged TransmitFile API.

    But to be able to use this API, you need a physical file to transfer. So here is a pseudo c# code that explain how to do this with a fictional myCacheFilePath physical file path. It also supports client caching possibilities. Of course, if you already have a file at hand, you don't need to create that cache:

        if (!File.Exists(myCacheFilePath))
        {
            LoadMyCache(...); // saves the file to disk. don't do this if your source is already a physical file (not stored in a db for example).
        }
    
        // we suppose user-agent (browser) cache is enabled
        // check appropriate If-Modified-Since header
        DateTime ifModifiedSince = DateTime.MaxValue;
        string ifm = context.Request.Headers["If-Modified-Since"];
        if (!string.IsNullOrEmpty(ifm))
        {
            try
            {
                ifModifiedSince = DateTime.Parse(ifm, DateTimeFormatInfo.InvariantInfo);
            }
            catch
            {
                // do nothing
            }
    
            // file has not changed, just send this information but truncate milliseconds
            if (ifModifiedSince == TruncateMilliseconds(File.GetLastWriteTime(myCacheFilePath)))
            {
                ResponseWriteNotModified(...); // HTTP 304
                return;
            }
        }
    
        Response.ContentType = contentType; // set your file content type here
        Response.AddHeader("Last-Modified", File.GetLastWriteTimeUtc(myCacheFilePath).ToString("r", DateTimeFormatInfo.InvariantInfo)); // tell the client to cache that file
    
        // this API uses windows lower levels directly and is not memory/cpu intensive on Windows platform to send one file. It also caches files in the kernel.
        Response.TransmitFile(myCacheFilePath)
    

提交回复
热议问题