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

こ雲淡風輕ζ 提交于 2021-01-05 11:34:11

问题


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?


回答1:


.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).



来源:https://stackoverflow.com/questions/59546230/what-is-the-difference-between-file-physicalfile-physicalfileresult-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!