Note that there are some explanatory texts on larger screens.

plurals
  1. POImpersonation in ASP.NET MVC
    text
    copied!<p>I have an Action that needs to read a file from a secure location, so I have to use impersonation to read the file.</p> <p>This code WORKS:</p> <pre><code>[AcceptVerbs(HttpVerbs.Get)] public ActionResult DirectDownload(Guid id) { if (Impersonator.ImpersonateValidUser()) { try { var path = "path to file"; if (!System.IO.File.Exists(path)) { return View("filenotfound"); } var bytes = System.IO.File.ReadAllBytes(path); return File(bytes, "application/octet-stream", "FileName"); } catch (Exception e) { Log.Exception(e); }finally { Impersonator.UndoImpersonation(); } } return View("filenotfound"); } </code></pre> <p>The only problem with the above code is that I have to read the entire file into memory and I am going to be dealing with VERY large files, so this is not a good solution. But if I replace these 2 lines:</p> <pre><code>var bytes = System.IO.File.ReadAllBytes(path); return File(bytes, "application/octet-stream", "FileName"); </code></pre> <p>with this:</p> <pre><code>return File(path, "application/octet-stream", "FileName"); </code></pre> <p>It does NOT work and I get the error message:</p> <blockquote> <p>Access to the path 'c:\projects\uploads\1\aa2bcbe7-ea99-499d-add8-c1fdac561b0e\Untitled 2.csv' is denied.</p> </blockquote> <p>I guess using the File results with a path, tries to open the file at a later time in the request pipeline when I have already "undone" the impersonation.</p> <p>Remember, the impersonation code works because I can read the file in the bytes array. What I want to do though is stream the file to the client.</p> <p>Any idea how I can work around this?</p> <p>Thanks in advance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload