Configure ASP.NET Core App to set new default files - asp.net-core

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.

Related

The fbx file can't load in ASP.NET core

I use three.js in my project. In developing front-end everything was OK, but after copy/past code in .cshtml files and migrate static files in wwwroot, a JavaScript file contatins threejs loader cannot load .fbx file. After run project give 404 error.
This code get .fbx file.
let loader = new FBXLoader();
loader.load("/fbx/earthfbx2.fbx", function (object) {
//do somethings
});
after some search, I improve problem by adding this lines of code in startup.cs Configure method
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".fbx"] = "application/octet-stream";
provider.Mappings[".myapp"] = "application/x-msdownload";
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
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

Upload Folders to Fileshare with ASP.NET Core Website

I want my Uploads folder to reside on a fileshare.
Reason why I want this: Redundant frontend.
So instead of saving to:
C:\inetpub\wwwroot\wwwroot\Uploads
Uploads should be saved to:
\\fileshare01\MyWebsite\Uploads
I am aware that VirtualDirectories exist. This works for reading from the fileshare but writing to the Uploads directory still writes to lokal drive.
So with VirtualDirectories I can access http://localhost/Uploads/myfile.png which is actually on the fileshare BUT new files are not written there!
Here (simplified) how I save files:
IFormFileCollection files = Request.Form.Files;
var file = files.First();
using (var stream = new FileStream(#"Uploads\myfile.png", FileMode.Create))
{
await file.CopyToAsync(stream);
}
When I try to save to the new network path as absolute path it seems I require higher permissions and end up with a 500.30 error. I guess because application pool user has too little permission which I think is a good thing.
My Question:
How is this problem solved as good-practice? Shouldn't everything work automagically when configuring a VirtualDirectory including writing?
Solved it. I just got the 500.30 error because of an error in my appconfig.json. I didn't escape the backslashes in my base path.
I found this blog post saying
There is no need to add a „virtual directory“ in IIS, this stuff is
deprecated
and explaining that this is the way it's done via Startup.cs Configure() method:
app.UseFileServer(new FileServerOptions
{
FileProvider = new PhysicalFileProvider(#"\\server\path"),
RequestPath = new PathString("/MyPath"),
EnableDirectoryBrowsing = false
});
Another configuration mystery of ASP.NET Core solved :)

Unable to change swagger ui path

I'm using Swagger / Swashbuckle version 5.6 to generate documentation for my ASP.Net Web API 2 project.
By default API documentation is accessible at URL http://localhost:56081/swagger/ui/index
But, I want it should be available at http://localhost:56081/apihelp/
I searched a lot, tried changing settings in the SwaggerConfig.cs file but nothing seems to make this work.
So, is this even possible? if yes, can anyone help me with this ?
You can add the path to the call of EnableSwaggereUi,
e.g.:
SwaggerConfig.Register(HttpConfiguration config)
{
config.EnableSwaggerUi("apihelp/{*assetPath}", c =>
... // following lines omitted
}
You can then call the UI with the URL http://localhost:56081/apihelp/index
See https://github.com/domaindrivendev/Swashbuckle#custom-routes for reference.
Please note: the default setting 'swagger' redirects automatically to 'swagger/ui/index', but this custom setting does not automaically redirect to 'apihelp/index' when you just use 'apihelp'.
To achieve an automatic redirect you can add the route in WebApiConfig:
config.Routes.MapHttpRoute(
name: "Swagger UI",
routeTemplate: "apihelp",
defaults: null,
constraints: null,
handler: new RedirectHandler(message => message.RequestUri.ToString().TrimEnd('/'), "/index"));
The redirect code is based on v.karbovnichy's answer in How to redirect from root url to /swagger/ui/index?

How can you use multiple directories for static files in an aspnet core app?

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/