How can you use multiple directories for static files in an aspnet core app? - asp.net-core

By default, the wwwroot directory can host static files. However, in some scenarios, it might be ideal to have two directories for static files. (For example, having webpack dump a build into one gitignored directory, and keeping some image files, favicon and such in a not-gitignored directory). Technically, this could be achieved by having two folders within the wwwroot, but it might organizationally preferable to have these folders at the root level. Is there a way to configure an aspnet core app to use two separate directories for static files?

Just register UseStaticFiles twice:
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "static"))
});
Now files will be found from wwwroot and static folders.

Registering UseStaticFiles twice won't solve it for MapFallbackToFile
An alternative approach.
// Build the different providers you need
var webRootProvider =
new PhysicalFileProvider(builder.Environment.WebRootPath);
var newPathProvider =
new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, #"Other"));
// Create the Composite Provider
var compositeProvider =
new CompositeFileProvider(webRootProvider, newPathProvider);
// Replace the default provider with the new one
app.Environment.WebRootFileProvider = compositeProvider;
https://wildermuth.com/2022/04/25/multiple-directories-for-static-files-in-aspnetcore/

Related

have a problem accessing the files in wwwroot

In the wwwroot folder I can access all files(images, java script, css, zip). But when I upload an apk file, it is not accessible.
When I compress this apk file to zip I can download it
AspNetCore uses this list of media types and according to this list, it does not know what an APK file is, so AspNetCore will return a 404 error.
To allow this, you can map your own. REF: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-6.0#fileextensioncontenttypeprovider
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".apk"] = "application/vnd.android.package-archive";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
});

ASP.NET Core can't see images when acceding by browser

I've created an ASP.NET Core 3.1 Web API project, on IIS Express it works perfectly with the controllers. I've created a folder called images and copied some .jpg files there.
My idea was get those images from my Xamarin app using the url, like
http://192.168.0.185:52493/img/lucas.PNG
but nothing is being returned. Then I've tried writing the url directly into Internet Explorer, but nothing happens, the image is not shown in the browser either.
Any idea what it can be?
If you would like to access your file from your own folder img located in the root of the project instead of the default wwwroot folder ,you need to configure the Static File Middleware in startup.cs Configure method like below:
app.UseStaticFiles();// For the wwwroot folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "img")),
RequestPath = "/img"
});
app.UseRouting();
//other middlewares
Refer to https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.2#serve-files-outside-of-web-root

Do I need to put css/js all in wwwroort folder in Asp.net Core? I am migrating from Older Mvc project

I want to use js/files outside wwwroot folder. How to Do that?
Yes, you can serve static files outside wwwroot.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles(); // For the wwwroot folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
RequestPath = "/StaticFiles"
});
}
See Serve files outside of web root.
But why do you want this?

Configure ASP.NET Core App to set new default files

I went thru the documentation provided for Use Static Files for ASP.NET core app. After Reading information from section Serving a default document & Using the UseFileServer method, following two questions are opened in my mind, respectively:
How can I add new default file if it is outside of wwwroot
How can I add new default file which is even under www using UseFileServer extension method
In your Startup.Configure method you can configure the default file:
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("myDefault.html"); // this had no influence :-(
app.UseDefaultFiles(options);
If I define the following options, I can load the default index.html through /StaticFiles but not my customized myDefault.html which is probably what you are after.
app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(#"C:\temp\"),
RequestPath = new PathString("/StaticFiles"),
EnableDefaultFiles = true,
EnableDirectoryBrowsing = false
});
UseDefaultFiles doesn't seem to have any influence. However it should still work if you configure the default file in your web server.
FileServerOptions has a property DefaultFiles, but it is read-only.

in asp.net 5 is it possible to store and read custom files in approot instead of wwwroot?

when you deploy an asp.net5/mvc6 app there is the wwwroot folder where web assets like css, js, images belong, and there is approot folder where packages and source code belong.
It seems that classes in the Microsoft.Framework.Configuration namespace for example must be able to read files from below approot since that is where config.json files would live.
What I want to know is, is it possible to store and read custom files of my own in approot? and if so how?
For example I'm not using Entity Framework so I need a place to put sql install and upgrade scripts and would prefer not to put them beneath wwwroot. I also have custom configuration files for things like navigation sitemap that I would rather not put below wwwroot if it is possible to put them elsewhere such as approot.
I know I can access files below wwwroot using IHostingEnvironment env.MapPath("~/somefileinwwwrootfoilder.json")
Is there a similar way to access files under approot?
The accepted answer is correct, but since a ASP.NET Core 1.0 release a few things have changed so I thought I'd write a new clear things up a bit.
What I did was create a folder in my project called AppData. You can call it anything you like.
Note: it's not in wwwroot because we want to keep this data private.
Next, you can use IHostingEnvironment to get access to the folder path. This interface can be injected as a dependency into some kind of helper service and what you end up with is something like this:
public class AppDataHelper
{
private readonly IHostingEnvironment _hostingEnvironment;
private const string _appDataFolder = "AppData";
public AppDataHelper(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public async Task<string> ReadAllTextAsync(string relativePath)
{
var path = Path.Combine(_hostingEnvironment.ContentRootPath, _appDataFolder, relativePath);
using (var reader = File.OpenText(path))
{
return await reader.ReadToEndAsync();
}
}
}
Additionally, to get things to deploy correctly I had to add the AppData folder to the publishOptions include list in project.json.
As mentioned in the comments, to deploy AppData folder correctly in ASP.NET MVC Core 2 (using *.csproj file, instead of project.json), syntax is as follows:
<ItemGroup>
<None Include="AppData\*" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
Yes, it is possible. Just get the path to your app folder and the pass it to configuration or whoever else needs it:
public class Startup
{
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var wwwrootRoot = env.WebRootPath;
var appRoot = appEnv.ApplicationBasePath;