简体   繁体   中英

Serve static files from controller

I have a .net 6 app that reads files from different zip files on startup and converts them to a list of Resources :

public class Resource
{
    public string? Id { get; set; }
    public string? MimeType { get; set; }
    public byte[] Data { get; set; } = Array.Empty<byte>();
}

Currently, I just keep them in a dictionary in memory and serve them from a controller:

[HttpGet("{id}")]
public IActionResult GetResource(string id)
{
    var resource = _resourceRepository.Get(id);

    return File(resource.Data, resource.MimeType!);
}

I would like to incorporate the static file management in the.net framework, but preferably retain the controller so that the clients can get resources using a GET resource/id .

I tried to use app.UseStaticFiles , set the RequestPath to "resource" and store the files without extension and set ServeUnknownFileTypes = true which works, I would prefer to keep the extensions to be able to browse the folders manually and keep the content-type header.

Is there any way to manage this through the controller?

I think you already knew that configuring static files middleware is necessary,

https://learn.microsoft.com/en-us/as.net/core/fundamentals/static-files?view=as.netcore-7.0

But you probably didn't notice that you can write your own file provider (instead of the default PhysicalFileProvider ),

https://learn.microsoft.com/en-us/as.net/core/fundamentals/file-providers?view=as.netcore-7.0

Microsoft ships an example of ManifestEmbeddedFileProvider but it might not work the way you like, so you'd better create your own.

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