简体   繁体   中英

What is the difference between File(), PhysicalFile(), PhysicalFileResult() in ASP.NET Core?

I am trying to build a Web API endpoint using ASP.NET core 3.1 what would allow an application to send me an id, and the response would be with the corresponding file.

Here is my method

[HttpGet("get")]
public IActionResult Get(Guid id)
{
    FoundFileInfo file = PathFinder.Get(id);

    if(file == null || !System.IO.File.Exists(file.Fullname))
    {
        return NotFound();
    }

    return File(file.Fullname, "image/jpeg");
}

using the same code, I can return File(file.VirtualName, "image/jpeg") , new PhysicalFileResult(filename, "image/jpeg") , or PhysicalFile(filename, "image/jpeg") . But what is the difference between them and what is the right use case for each?

My end goal is to allow the consumer to construct an instance of IFileInfo from the response of my endpoint. Somehow I would want to give the consumer enough info like LastModified , Length , Name , PhysicalPath . Which method is the right method to use for my case?

.NET Core's File handles only virtual paths (relative within your website). The PhysicalFile handles physical (absolute) file paths.

PhysicalFile is just a facade that returns the PhysicalFileResult . But you can just return it manually with new PhysicalFileResult .

I don't think there are other differences, the choice depends then mostly on how are you able to obtain the location of the file you want to return. If you have both a virtual and physical location, you can pick any of the two ( File or PhysicalFile ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM