Blog

Filter posts by Category Or Tag of the Blog section!

Working with Static Files in asp.net core

Saturday, 28 July 2018

In asp.net core,  the wwwroot folder treated as a web root folder. Static files can be stored in any folder under the web root and accessed with a relative path to that root. By default, static files are not accessible:

In order to access a file you should add the related configuration in Configure method of Startup class:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseStaticFiles();
         }

By running again the project, the image will be accessible:

Now if you want to do more configuration for other paths inside wwwroot, for example, directory browsing or inner static file, you can add the configuration below:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseStaticFiles();

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

            app.UseDirectoryBrowser(new DirectoryBrowserOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")),
                RequestPath = "/Images"
            });

            app.UseHttpsRedirection();
            app.UseMvc();
        }

It's obviously shown that the Images is a folder inside wwwroot, look at the output below:

Category: Software

Tags: Asp.Net

comments powered by Disqus