Table of Contents
Asp.Net Core-Exception Handling
Asp.Net Core static file
Case
Home Backend Development C#.Net Tutorial ASP.NET Core Example Tutorial: Exception Handling and Static File Tutorial

ASP.NET Core Example Tutorial: Exception Handling and Static File Tutorial

Jun 16, 2017 am 10:08 AM

<h1 id="Asp-Net-Core-Exception-Handling">Asp.Net Core-Exception Handling</h1> <ol class=" list-paddingleft-2"><li><p>Asp.Net Core-Exception Handling</p></li></ol> <p>In this chapter, we will discuss exceptions and error handling. When an error occurs in an ASP.NET Core application, you can handle it in a variety of different ways. Let's look at handling exceptions by adding a middleware that will help us handle errors. </p> <p>To simulate an error, let's go to the application, run it, and see how the program behaves if we just throw an exception. </p> <p class="cnblogs_code"><br></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> 1 using Microsoft.AspNet.Builder;   2 using Microsoft.AspNet.Hosting;   3 using Microsoft.AspNet.Http;   4 using Microsoft.Extensions.DependencyInjection;   5 using Microsoft.Extensions.Configuration;    6 namespace FirstAppDemo {   7    public class Startup {   8       public Startup() {   9          var builder = new ConfigurationBuilder()  10             .AddJsonFile("AppSettings.json");  11          Configuration = builder.Build();  12       }   13       public IConfiguration Configuration { get; set; }   14          15       // This method gets called by the runtime.  16       // Use this method to add services to the container.  17       // For more information on how to configure your application,  18       // visit http://go.microsoft.com/fwlink/?LinkID=398940 19       public void ConfigureServices(IServiceCollection services) {  20       }   21        22       // This method gets called by the runtime.  23       // Use this method to configure the HTTP request pipeline.24       public void Configure(IApplicationBuilder app) {  25          app.UseIISPlatformHandler();   26          app.UseRuntimeInfoPage();   27           28          app.Run(async (context) => {  29             throw new System.Exception("Throw Exception");  30             var msg = Configuration["message"];  31             await context.Response.WriteAsync(msg);  32          });   33       }   34          35       // Entry point for the application. 36       public static void Main(string[] args) => WebApplication.Run<Startup>(args);  37    }    38 }</pre><div class="contentsignin">Copy after login</div></div> <p> </p> <p> </p> <p> </p> <p>It will only throw a very general exception message. Save the Startup.cs page and run your application. </p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/470d228a9709dbe93d976747550661ed-0.jpg" class="lazy" alt=""></p> <p>You will see that we failed to load this resource. There was an HTTP 500 error, Internal Server Error, and that page wasn't very helpful. It may be convenient to get some exception information. </p> <p>Let's add another middleware UseDeveloperExceptionPage. </p> <p class="cnblogs_code"><br></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> 1 // This method gets called by the runtime.    2 // Use this method to configure the HTTP request pipeline.  3 public void Configure(IApplicationBuilder app) {   4    app.UseIISPlatformHandler();    5    app.UseDeveloperExceptionPage();   6    app.UseRuntimeInfoPage();    7      8    app.Run(async (context) => {   9       throw new System.Exception("Throw Exception");  10       var msg = Configuration["message"];  11       await context.Response.WriteAsync(msg);  12    });   13 }14</pre><div class="contentsignin">Copy after login</div></div> <p> </p> <p> </p> <p>This middleware is a little different from the others. Other middleware usually listens for incoming requests and performs operations on the requests. some responses. </p> <p>UseDeveloperExceptionPage does not care so much about what happens to the incoming request later in the pipeline. </p> <p>It just calls the next middleware, and then waits to see if there will be an exception in the pipeline. If there is an exception, this middleware will give you an error page about the exception. </p> <p>Now let’s run the application again. This will produce an output as shown in the screenshot below. </p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/470d228a9709dbe93d976747550661ed-1.jpg" class="lazy" alt=""></p> <p>Now if an exception occurs in the program, you will see some exception information you want to see on the page. You'll also get a stack trace: Here you can see that an unhandled exception was thrown on line 37 of Startup.cs. </p> <p>All this exception information will be very useful to developers. In fact, we may only want these exception messages to be displayed when the developer runs the application. </p> <p> </p> <h1 id="Asp-Net-Core-static-file">Asp.Net Core static file</h1> <ol class=" list-paddingleft-2"> <li><p>Asp.Net Core static file</p></li> <li><p>Case</p></li> </ol> <p>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. </p> <ul class=" list-paddingleft-2"> <li><p>Static files like JavaScript files, images, CSS files, etc., our Asp.Net Core applications can be provided directly to customers. </p></li> <li><p>Static files are usually located in the web root (wwwroot) folder. </p></li> <li><p>By default, this is the only place where we can serve files directly from the file system. </p></li> </ul> <p> </p> <hr> <h2 id="Case">Case</h2> <p>Now let us go through a simple example to understand how we serve these static files in our application. </p> <p>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. </p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/470d228a9709dbe93d976747550661ed-2.jpg" class="lazy" alt=""></p> <p>In the middle pane, select the HTML page and call it index.html, click the Add button. </p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/470d228a9709dbe93d976747550661ed-3.jpg" class="lazy" alt=""></p> <p>You will see a simple index.html file. Let's add some simple text and title in it as shown below. </p> <p class="syntaxhighlighter html"><br></p> <table border="0"><tbody><tr class="firstRow"> <td class="gutter">##1<p class="line number1 index0 alt2"></p>2<p class="line number2 index1 alt1"></p>3<p class="line number3 index2 alt2"></p>4<p class="line number4 index3 alt1"></p>5<p class="line number5 index4 alt2"></p>6<p class="line number6 index5 alt1"></p>7<p class="line number7 index6 alt2"></p>8<p class="line number8 index7 alt1"></p>9<p class="line number9 index8 alt2"></p>10<p class="line number10 index9 alt1"></p> </td> <td class="code"> <p class="container"><br></p>##<!DOCTYPE html> <p class="line number1 index0 alt2"><code class="html plain"></code></p><<p class="line number2 index1 alt1"><code class="html plain">html</code><code class="html keyword">> <code class="html plain"></code> <p class="line number3 index2 alt2"><code class="html spaces"><</code><code class="html plain">head</code><code class="html keyword">> </code><code class="html plain"><p class="line number4 index3 alt1"><code class="html spaces">      </code><code class="html plain"><</code><code class="html keyword">meta</code> <code class="html color1">charset</code><code class="html plain">=</code><code class="html string">"utf-8"</code> <code class="html plain">/> </code></p> <p class="line number5 index4 alt2"><code class="html spaces">      </code><code class="html plain"><</code><code class="html keyword">title</code><code class="html plain">>Welcome to ASP.NET Core</</code><code class="html keyword">title</code><code class="html plain">> </code></p> <p class="line number6 index5 alt1"><code class="html spaces">   </code><code class="html plain"></</code><code class="html keyword">head</code><code class="html plain">> </code></p> <p class="line number7 index6 alt2"><code class="html spaces">   </code><code class="html plain"><</code><code class="html keyword">body</code><code class="html plain">> </code></p> <p class="line number8 index7 alt1"><code class="html spaces">      </code><code class="html plain">Hello, Wolrd! this message is from our first static HTML file.  </code></p> <p class="line number9 index8 alt2"><code class="html spaces">   </code><code class="html plain"></</code><code class="html keyword">body</code><code class="html plain">> </code></p> <p class="line number10 index9 alt1"><code class="html plain"></</code><code class="html keyword">html</code><code class="html plain">></code></p></code></p> </td> </tr></tbody></table> <p>当您运行应用程序并在浏览器中输入index.html时,您将看到app.Run中间件将抛出一个异常,因为目前在我们的应用程序中什么都没有。</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/315d89c3796749d419a682e7ec51873a-4.jpg" class="lazy" alt=""></p> <p>现在我们的项目中没有中间件会去找文件系统上的任何文件。</p> <p>为了解决这个问题,通过在解决方案资源管理器中右键单击您的项目并选择管理NuGet包进入到NuGet包管理器。</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/315d89c3796749d419a682e7ec51873a-5.jpg" class="lazy" alt=""></p> <p>搜索 Microsoft.AspNet.StaticFiles,会找到静态文件中间件。让我们安装此 nuget 程序包,现在我们可以在Configure方法中注册中间件。</p> <p>让我们在下面的程序中所示的Configure方法中添加 UseStaticFiles 中间件。</p> <p class="cnblogs_code"><br></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> 1 using Microsoft.AspNet.Builder;   2 using Microsoft.AspNet.Hosting;   3 using Microsoft.AspNet.Http;   4 using Microsoft.Extensions.DependencyInjection;   5 using Microsoft.Extensions.Configuration;    6 namespace FirstAppDemo {   7    public class Startup {   8       public Startup() {   9          var builder = new ConfigurationBuilder()  10             .AddJsonFile("AppSettings.json");  11          Configuration = builder.Build();  12       }   13       public IConfiguration Configuration { get; set; }   14        15       // This method gets called by the runtime.  16       // Use this method to add services to the container.  17       // For more information on how to configure your application,  18       // visit http://go.microsoft.com/fwlink/?LinkID=398940 19       public void ConfigureServices(IServiceCollection services) {  20       }   21        22       // This method gets called by the runtime.   23       // Use this method to configure the HTTP request pipeline. 24       public void Configure(IApplicationBuilder app) {  25          app.UseIISPlatformHandler();   26          app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage();  27          app.UseStaticFiles();  28           29          app.Run(async (context) => {  30             throw new System.Exception("Throw Exception");  31             var msg = Configuration["message"];  32             await context.Response.WriteAsync(msg);  33          });  34       }   35          36       // Entry point for the application. 37       public static void Main(string[] args) => WebApplication.Run<Startup>(args);  38    }  39 }</pre><div class="contentsignin">Copy after login</div></div> <p>除非你通过传入一些不同的配置参数来覆盖选项,否则静态文件会对于一个给定的请求看作是请求路径。这个请求路径是相对于文件系统。</p> <ul class=" list-paddingleft-2"> <li><p>如果静态文件根据url找到一个文件,它将直接返回该文件,而不调用下一个块中间件。</p></li> <li><p>如果没有找到匹配的文件,那么它会继续执行下一个块中间件。</p></li> </ul> <p>让我们保存Startup.cs文件并刷新浏览器。</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/315d89c3796749d419a682e7ec51873a-6.jpg" class="lazy" alt=""></p> <p>你现在可以看到index.html文件。你放置在wwwroot文件夹下任何地方的任何JavaScript文件、CSS文件或者HTML文件,您都能够在Asp.Net Core中直接当静态文件使用。</p> <ul class=" list-paddingleft-2"> <li><p>在如果你想 让index.html作为您的默认文件,IIS一直有这种功能。</p></li> <li><p>你可以给 IIS 一个默认文件列表。如果有人访问根目录,在这种情况下,如果 IIS 找到命名为 index.html的文件,它就会自动将该文件返回给客户端。</p></li> <li><p>让我们现在开始进行少量更改。首先,我们需要删除强制的错误,然后添加另一块的中间件,这就是 UseDefaultFiles。以下是配置方法的实现。</p></li> <li> <p class="cnblogs_code"><br></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> 1 / This method gets called by the runtime.    2 // Use this method to configure the HTTP request pipeline.  3 public void Configure(IApplicationBuilder app)  {   4    app.UseIISPlatformHandler();    5    app.UseDeveloperExceptionPage();   6      7    app.UseRuntimeInfoPage();    8    app.UseDefaultFiles();   9    app.UseStaticFiles();   10     11    app.Run(async (context) => {  12       var msg = Configuration["message"];  13       await context.Response.WriteAsync(msg);  14    });   15 }</pre><div class="contentsignin">Copy after login</div></div> <p> </p> </li> </ul> <p> </p> <ul class=" list-paddingleft-2"> <li><p>这段中间件将监听传入的请求,如果请求是根目录,就查看是否有匹配的默认文件。</p></li> <li><p>您可以覆盖这个中间件的选项来告诉它如何匹配默认文件,但index.html是默认情况下的一个默认的文件。</p></li> </ul> <p>让我们保存 Startup.cs 文件并将您的浏览器转到 web 应用程序的根目录。</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/315d89c3796749d419a682e7ec51873a-7.jpg" class="lazy" alt=""></p> <p>你现在可以看到index.html是默认文件。你安装中间件的顺序是很重要的,因为如果你将UseDefaultFiles放置在UseStaticFiles之后,你将可能不会得到相同的结果。</p> <p>如果你想要使用UseDefaultFiles和UseStaticFiles中间件,你可以使用另一个中间件Microsoft.aspnet.staticfiles,它也是NuGet包,它是一个服务器中间件。这本质上是以正确的顺序包含了默认文件和静态文件。</p> <p class="cnblogs_code"><br></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> 1 // This method gets called by the runtime.    2 // Use this method to configure the HTTP request pipeline.  3 public void Configure(IApplicationBuilder app) {   4    app.UseIISPlatformHandler();    5    app.UseDeveloperExceptionPage();   6      7    app.UseRuntimeInfoPage();    8    app. UseFileServer();    9     10    app.Run(async (context) => {  11       var msg = Configuration["message"];  12       await context.Response.WriteAsync(msg);  13    });  14 }</pre><div class="contentsignin">Copy after login</div></div> <p> </p> <p> </p> <p>让我们再一次保存 Startup.cs 文件。一旦你刷新浏览器,你将看到相同的结果,如下面的屏幕快照所示。</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/001/506/b33e085c39ca50d6c54911a15965303c-8.jpg" class="lazy" alt=""></p>

The above is the detailed content of ASP.NET Core Example Tutorial: Exception Handling and Static File Tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C++ function exceptions and multithreading: error handling in concurrent environments C++ function exceptions and multithreading: error handling in concurrent environments May 04, 2024 pm 04:42 PM

Function exception handling in C++ is particularly important for multi-threaded environments to ensure thread safety and data integrity. The try-catch statement allows you to catch and handle specific types of exceptions when they occur to prevent program crashes or data corruption.

What is the relationship between recursive calls and exception handling in Java functions? What is the relationship between recursive calls and exception handling in Java functions? May 03, 2024 pm 06:12 PM

Exception handling in recursive calls: Limiting recursion depth: Preventing stack overflow. Use exception handling: Use try-catch statements to handle exceptions. Tail recursion optimization: avoid stack overflow.

How does C++ exception handling support custom error handling routines? How does C++ exception handling support custom error handling routines? Jun 05, 2024 pm 12:13 PM

C++ exception handling allows the creation of custom error handling routines to handle runtime errors by throwing exceptions and catching them using try-catch blocks. 1. Create a custom exception class derived from the exception class and override the what() method; 2. Use the throw keyword to throw an exception; 3. Use the try-catch block to catch exceptions and specify the exception types that can be handled.

How to handle exceptions in C++ Lambda expressions? How to handle exceptions in C++ Lambda expressions? Jun 03, 2024 pm 03:01 PM

Exception handling in C++ Lambda expressions does not have its own scope, and exceptions are not caught by default. To catch exceptions, you can use Lambda expression catching syntax, which allows a Lambda expression to capture a variable within its definition scope, allowing exception handling in a try-catch block.

Exception handling in C++ technology: How to handle exceptions correctly in a multi-threaded environment? Exception handling in C++ technology: How to handle exceptions correctly in a multi-threaded environment? May 09, 2024 pm 12:36 PM

In multithreaded C++, exception handling follows the following principles: timeliness, thread safety, and clarity. In practice, you can ensure thread safety of exception handling code by using mutex or atomic variables. Additionally, consider reentrancy, performance, and testing of your exception handling code to ensure it runs safely and efficiently in a multi-threaded environment.

PHP exception handling: understand system behavior through exception tracking PHP exception handling: understand system behavior through exception tracking Jun 05, 2024 pm 07:57 PM

PHP exception handling: Understanding system behavior through exception tracking Exceptions are the mechanism used by PHP to handle errors, and exceptions are handled by exception handlers. The exception class Exception represents general exceptions, while the Throwable class represents all exceptions. Use the throw keyword to throw exceptions and use try...catch statements to define exception handlers. In practical cases, exception handling is used to capture and handle DivisionByZeroError that may be thrown by the calculate() function to ensure that the application can fail gracefully when an error occurs.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

Exception handling in C++ technology: How to optimize the performance of exception handling? Exception handling in C++ technology: How to optimize the performance of exception handling? May 09, 2024 am 10:39 AM

In order to optimize exception handling performance in C++, the following four techniques can be implemented: Avoid unnecessary exception throwing. Use lightweight exception classes. Prioritize efficiency and design exception classes that contain only necessary information. Take advantage of compiler options to achieve the best balance of performance and stability.

See all articles