aspdotnet_webroot.md - brainchildservices/curriculum GitHub Wiki
WEB ROOT:
- The web root is the base path for public, static resource files, such as:
- Stylesheets (.css)
- JavaScript (.js)
- Images (.png, .jpg)
- Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.
- By default, static files are served only from the web root directory and its sub-directories.
- The web root path defaults to {content root}/wwwroot.
- It is possible to Specify a different web root by setting its path when building the host.
- In Razor .cshtml files, tilde-slash (~/) points to the web root. A path beginning with ~/ is referred to as a virtual path.
-
Static files are stored within the project's web root directory.
-
The default directory is {content root}/wwwroot, but it can be changed with the UseWebRoot method.
-
The CreateDefaultBuilder method sets the content root to the current directory:
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
-
Static files are accessible via a path relative to the web root. For example, the Web Application project templates contain several folders within the wwwroot folder:
- wwwroot
- css
- js
- lib
- wwwroot
-
Consider creating the wwwroot/images folder and adding the wwwroot/images/MyImage.jpg file. The URI format to access a file in the images folder is https:///images/<image_file_name>. For example, https://localhost:5001/images/MyImage.jpg
- Serve files in web root
-
The default web app templates call the UseStaticFiles method in Startup.Configure, which enables static files to be served:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); }
-
The parameterless UseStaticFiles method overload marks the files in web root as servable. The following markup references wwwroot/images/MyImage.jpg:
<img src="~/images/MyImage.jpg" class="img" alt="My image" />
-
In the preceding code, the tilde character ~/ points to the web root.
-