


Detailed introduction to the tutorial on using ASP.NET Core static files
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!

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

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.

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

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.

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

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# 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor