InvalidOperationException on File return

Jak*_*ary 11 c# asp.net asp.net-mvc .net-core asp.net-core

am running into some weird issue when i try to return a file to be downloaded, so this is my code

string filePath = Path.Combine(Path1, Path2, filename);
return File(filePath, "audio/mp3", "myfile.mp3");
Run Code Online (Sandbox Code Playgroud)

but the problem it return this error

InvalidOperationException: No file provider has been configured to process the supplied file.

am not sure what i have missed, any help ?

Wil*_*ang 11

您可以简单地从以下位置更改代码:

string filePath = Path.Combine(Path1, Path2, filename);
return File(filePath, "audio/mp3", "myfile.mp3");
Run Code Online (Sandbox Code Playgroud)

对此:

string filePath = Path.Combine(Path1, Path2, filename);
return PhysicalFile(filePath, "audio/mp3", "myfile.mp3");
Run Code Online (Sandbox Code Playgroud)

然后问题解决了!

您还可以将文件放在文件wwwroot夹(您的Web 根文件夹)下。然后你可以使用相对路径Web根文件夹,并把filePath进入的第一个参数文件的方法。然后您可以毫无问题地访问该文件。这将比使用PhysicalFile方法安全得多。


Jak*_*ary 5

因此,返回 File 方法的方法与 @SeM 建议的一样,但通过从文件路径中删除文件名来实现。

string filePath = Path.Combine(Path1, Path2);

IFileProvider provider = new PhysicalFileProvider(filePath);
IFileInfo fileInfo = provider.GetFileInfo(filename);
var readStream = fileInfo.CreateReadStream();

return File(readStream, "audio/mpeg", fileName);
Run Code Online (Sandbox Code Playgroud)