search
HomeBackend DevelopmentC#.Net TutorialDetailed introduction to the tutorial on using ASP.NET Core static files

Detailed introduction to the tutorial on using ASP.NET Core static files

Jun 19, 2017 am 10:12 AM
asp.netcoreintroducedetailedstatic

This article mainly introduces the usage tutorial of ASP.NET Core static files in detail, which has certain reference value. Interested friends can refer to it

In this chapter, we will learn how to use files. Almost every web application needs an important feature: the ability to serve files (static files) from the file system .

  • Static files like JavaScript files, images, CSS files, etc., our Asp.Net Core application can provide directly to customers.

  • Static files are usually located in the web root (wwwroot) folder.

  • By default, this is the only place where we can serve files directly from the file system.

Case

Now let us go through a simple example to understand how we serve these static files in our application.

Here we want to add a simple HTML file to our FirstAppDemo application, placed in the web root (wwwroot) folder. Right-click on the wwwroot folder in Solution Explorer and select Add → New Item.

In the middle pane, select the HTML page and call it index.html, click the Add button.

You will see a simple index.html file. Let's add some simple text and title in it as shown below.


<!DOCTYPE html> 
<html> 
 <head> 
 <meta charset="utf-8" /> 
 <title>Welcome to ASP.NET Core</title> 
 </head> 
 <body> 
 Hello, Wolrd! this message is from our first static HTML file. 
 </body> 
</html>

When you run the application and enter index.html in the browser, you will see that app.RunMiddleware will throw An exception because currently there is nothing in our application.

#Now no middleware in our project will look for any files on the file system.

To resolve this issue, enter the NuGet Package Manager by right-clicking your project in Solution Explorer and selecting Manage NuGet Packages.

Search Microsoft.AspNet.StaticFiles and you will find the static file middleware. Let's install this nuget package and now we can register the middleware in the Configure method.

Let us add UseStaticFiles middleware in the Configure method shown in the program below.


using Microsoft.AspNet.Builder; 
using Microsoft.AspNet.Hosting; 
using Microsoft.AspNet.Http; 
using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Configuration; 
namespace FirstAppDemo { 
 public class Startup { 
 public Startup() { 
  var builder = new ConfigurationBuilder() 
  .AddJsonFile("AppSettings.json"); 
  Configuration = builder.Build(); 
 } 
 public IConfiguration Configuration { get; set; } 
 
 // This method gets called by the runtime. 
 // Use this method to add services to the container. 
 // For more information on how to configure your application, 
 // visit http://go.microsoft.com/fwlink/?LinkID=398940 
 public void ConfigureServices(IServiceCollection services) { 
 } 
 
 // This method gets called by the runtime. 
 // Use this method to configure the HTTP request pipeline. 
 public void Configure(IApplicationBuilder app) { 
  app.UseIISPlatformHandler(); 
  app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage(); 
  app.UseStaticFiles(); 
  
  app.Run(async (context) => { 
  throw new System.Exception("Throw Exception"); 
  var msg = Configuration["message"]; 
  await context.Response.WriteAsync(msg); 
  }); 
 } 
  
 // Entry point for the application. 
 public static void Main(string[] args) => WebApplication.Run<Startup>(args); 
 } 
}

Unless you override the options by passing in some different configuration parameters, static files will be treated as the request path for a given request. This request path is relative to the file system.

  • If the static file finds a file based on the url, it will return the file directly without calling the next block middleware.

  • If no matching file is found, then it will continue executing the next block middleware.

Let’s save the Startup.cs file and refresh the browser.

You can now see the index.html file. Any JavaScript file, CSS file or HTML file you place anywhere under the wwwroot folder can be used directly as a static file in Asp.Net Core.

  • If you want index.html as your default file, IIS has always had this functionality.

  • You can give IIS a default file list. If someone accesses the root directory, in this case, if IIS finds a file named index.html, it will automatically return that file to the client.

  • Let's start making a few changes now. First, we need to remove the forced errors and then add another piece of middleware, which is UseDefaultFiles. The following is the implementation of the configuration method.


/ This method gets called by the runtime. 
// Use this method to configure the HTTP request pipeline. 
public void Configure(IApplicationBuilder app) { 
 app.UseIISPlatformHandler(); 
 app.UseDeveloperExceptionPage(); 
 
 app.UseRuntimeInfoPage(); 
 app.UseDefaultFiles(); 
 app.UseStaticFiles(); 
 
 app.Run(async (context) => { 
 var msg = Configuration["message"]; 
 await context.Response.WriteAsync(msg); 
 }); 
}

This middleware will listen for incoming requests. If the request is for the root directory, check whether there is a matching default file.

You can override the options of this middleware to tell it how to match the default file, but index.html is a default file by default.

Let’s save the Startup.cs file and go to your browser to the root directory of the web application.

你现在可以看到index.html是默认文件。你安装中间件的顺序是很重要的,因为如果你将UseDefaultFiles放置在UseStaticFiles之后,你将可能不会得到相同的结果。

如果你想要使用UseDefaultFiles和UseStaticFiles中间件,你可以使用另一个中间件Microsoft.aspnet.staticfiles,它也是NuGet包,它是一个服务器中间件。这本质上是以正确的顺序包含了默认文件和静态文件。

// This method gets called by the runtime. 
// Use this method to configure the HTTP request pipeline. 
public void Configure(IApplicationBuilder app) { 
 app.UseIISPlatformHandler(); 
 app.UseDeveloperExceptionPage(); 
 
 app.UseRuntimeInfoPage(); 
 app. UseFileServer(); 
 
 app.Run(async (context) => { 
 var msg = Configuration["message"]; 
 await context.Response.WriteAsync(msg); 
 }); 
}

让我们再一次保存 Startup.cs 文件。一旦你刷新浏览器,你将看到相同的结果,如下面的屏幕快照所示。

The above is the detailed content of Detailed introduction to the tutorial on using ASP.NET Core static files. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.