DotNet Controller to Return Static File

萝らか妹 提交于 2021-01-29 07:40:27

问题


I am trying to tell the controller to return a static file in some condition. I tried many ways "Server.MapPath" doesn't work for me so i need an alternative. i tried following but i get an error:

return File(Url.Content(startupPath), "text/javascript");

the error is:

InvalidOperationException: No file provider has been configured to process the supplied file.
Microsoft.AspNetCore.Mvc.Infrastructure.VirtualFileResultExecutor.GetFileInformation(VirtualFileResult result)

I have app.UseStaticFiles() and app.UseSpaStaticFiles(); both set.


回答1:


Having a controller return a file is something different than enabling static files or static spa files.

Static files:

From the Static files in ASP.NET Core:

Static files are stored within the project's web root directory. The default directory is /wwwroot. (...) The app's web host must be made aware of the content root directory. (...) Static files are accessible via a path relative to the web root. (...) The URI format to access a file in a subfolder is http:///subfolder/.

using the app.UseStaticFiles() will allow anyone to receive files from within your wwwroot directory.

This might satisfy your conditions. If it does not, because you might want to add authentication to receiving the file or return a different file from the same route based on a query parameter or the current user or you need to generate the file, you need to return the file from acontroller.

Returning a file from a controller:

there isn't a lot of microsoft documentation on this, but there are a lot of Q&A's on stackoverflow.

Checkout:

  • Returning a file to View/Download in ASP.NET MVC
  • How to return a file (FileContentResult) in ASP.NET WebAPI

public ActionResult DownloadFile()
{
    string filename = "File.pdf";
    string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Path/To/File/" + filename;
    byte[] filedata = System.IO.File.ReadAllBytes(filepath);
    string contentType = MimeMapping.GetMimeMapping(filepath);

   var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = filename,
        Inline = true,
    };

    Response.AppendHeader("Content-Disposition", cd.ToString());

    return File(filedata, contentType);
}

One of your problems also seems to be finding the file you want to return. You can use Server.MapPath("~/filename.ext") for this. Make sure your file is included in your compiled project by selecting 'Copy if newer' or 'Copy always' in it's properties at 'Copy to Output Directory'.



来源:https://stackoverflow.com/questions/58188286/dotnet-controller-to-return-static-file

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