Setting the server to serve static files

ASP.NET Core, by default, doesn't serve static files to end users. Even though the content root and web root paths have default values, you have to explicitly indicate that static files should be served. To do so, open the Startup.cs file, locate the Configure method, and add the following line:

app.UseStaticFiles();

Once this is placed in the right location, the ASP.NET Core platform will serve static files from the web root folder.

Make sure that the web root folder itself is not part of the URL. The following table demonstrates the physical file location and the matching URL, assuming that the default web root path, wwwroot, hasn't been changed:

Physical file location

URL

wwwroot/images/logo.png

http://example.com/images/logo.png

wwwroot/css/main.css

http://example.com/css/main.css

wwwroot/readme.txt

http://example.com/readme.txt

 

In addition to the Web root folder, it is possible to serve static files that reside in other directories. In order to do so, you need to pass parameters to the UseStaticFiles method. For example, the following code sample sets the assets folder as a static file folder under the /assets URL:

app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "assets")),
RequestPath = new PathString("/assets")
});

To add multiple static file paths, call the UseStaticFiles method multiple times. For example, the following piece of code sets the default Web root as a static file folder, as well as two other folders, images and videos:

app.UseStaticFiles(); // web root

app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "images")),
RequestPath = new PathString("/images")
});

app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "videos")),
RequestPath = new PathString("/videos")
});
If possible, try to avoid using static folders other than wwwroot. The wwwroot is the standard static directory in ASP.NET Core, and other developers who dive into your code will have an easier time understanding it if you stick to common practices.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.141.219