Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of exception handling and static Files in asp.net core

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of exception handling and static files in asp.net core, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

Asp.Net Core- exception handling

Asp.Net Core- exception handling

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 take a look at handling exceptions by adding a middleware that will help us handle errors.

To simulate an error, let's go to the application, run it, and see how the program works if we just throw an exception.

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} 3435 / / Entry point for the application. 36 public static void Main (string [] args) = > WebApplication.Run (args); 37} 38}

It only throws a very general exception message. Save the Startup.cs page and run your application.

You will see that we failed to load this resource. There is a HTTP 500error, internal server error, that page is not very helpful. It may be easy to get some abnormal information.

Let's add another middleware UseDeveloperExceptionPage.

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

This middleware is a little different from other middleware, which usually listens to incoming requests and responds to them.

UseDeveloperExceptionPage doesn't care so much about what happens later in the pipeline of incoming requests.

It just calls the next middleware and then waits to see if there is an exception in the pipeline. If there is an exception, the middleware will give you an error page about the exception.

Now let's run the application again. An output will be produced as shown in the screenshot below.

Now if there is an exception in the program, you will see some of the exception information you want to see on the page. You'll also get a stack trace: here you can see that line 37 of Startup.cs has an unhandled exception thrown.

All of this exception information will be very useful to developers. In fact, we may only want to display these exception messages when the developer runs the application.

Asp.Net Core static file

Asp.Net Core static file

Case

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

Static files such as JavaScript files, pictures, CSS files, etc., can be provided directly to customers by our Asp.Net Core application.

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

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

Case

Now let's use a simple example to see how we provide these static files in our application.

Here, we want to add a simple HTML file to our FirstAppDemo application, which is placed in the web root (wwwroot) folder. Right-click the wwwroot folder in solution Explorer and select the Add → new item.

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

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

one

two

three

four

five

six

seven

eight

nine

ten

Welcome to ASP.NET Core

Hello, Wolrd! This message is from our first static HTML file.

When you run the application and type index.html in your browser, you will see that app.Run middleware will throw an exception because there is currently nothing in our application.

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

To solve this problem, go to the NuGet package manager by right-clicking your project in solution Explorer and selecting manage NuGet package.

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

Let's add UseStaticFiles middleware to the Configure method shown in the following program.

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} 3536 / / Entry point for the application. 37 public static void Main (string] args) = > WebApplication.Run (args); 38} 39}

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

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

If no matching file is found, it moves on to 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 that you put anywhere under the wwwroot folder, you can use it directly as a static file in Asp.Net Core.

If you want index.html to be your default file, IIS has always had this feature.

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

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

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}

This middleware listens for incoming requests and, if the request is root, checks to see if there is a matching default file.

You can override the option 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 change your browser to the root directory of the web application.

You can now see that index.html is the default file. The order in which you install the middleware is important, because if you put UseDefaultFiles after UseStaticFiles, you may not get the same result.

If you want to use UseDefaultFiles and UseStaticFiles middleware, you can use another middleware Microsoft.aspnet.staticfiles, which is also the NuGet package, which is a server middleware. This essentially contains default and static files in the correct order.

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}

Let's save the Startup.cs file again. Once you refresh your browser, you will see the same results, as shown in the screenshot below.

Thank you for reading this article carefully. I hope the article "exception handling and sample Analysis of static Files in asp.net core" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report