exception handling and static files tutorial for ASP. NET Core Instance Tutorial

Source: Internet
Author: User
Tags stack trace

ASP. NET core-exception handling

    1. ASP. NET core-exception handling

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 take a look at the addition of a middleware to handle exceptions, and this middleware will help us handle errors.

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


 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 Configur Ationbuilder () 10. Addjsonfile ("Appsettings.json"); One Configuration = Builder. Build ();  Public iconfiguration Configuration {get; set;} Called/This method gets the runtime. //Use this method to add services to the container. +/For information Configure your application, +//visit Http://go.microsoft.com/fwlink/?L inkid=398940 public void Configureservices (Iservicecollection services) {$}//This Method gets called by the runtime. /Use this method to configure the HTTP request pipeline.24 public void ConfIgure (Iapplicationbuilder app) {app.  Useiisplatformhandler (); App.  Useruntimeinfopage (); App. Run (Async (context) = {throw new System.Exception ("Throw Exception"); var msg = Configu ration["message"]; Await the context. Response.writeasync (msg);  32}); Entry point for the application. N-public static void Main (string[] args) = webapplication.run<startup> (args); 37} 38}

It will only throw a very generic exception message. Save the Startup.cs page and run your application.

You will see that we failed to load this resource. An HTTP 500 error occurred with an internal server error, and that page was not very helpful. It may be convenient to get some exception 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    Apps. Usedeveloperexceptionpage ();  6    Apps. Useruntimeinfopage ();   7      8    apps. Run (Async (context) = {  9       throw new System.Exception ("Throw Exception");       var msg = configuration[" Message "];       await the context. Response.writeasync (msg);    });  13}14

This middleware is a bit different from the others, and other middleware usually listens for incoming requests and responds to requests.

Usedeveloperexceptionpage will not be so concerned about what happens to incoming requests after the pipeline.

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

Now let's run the application again. will produce an output as shown in the following screen.

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

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

ASP. NET Core static file

    1. ASP. NET Core static file

    2. Case

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

    • Static files like JavaScript files, images, CSS files, and so on, our ASP. NET core application can be directly provided to customers.

    • Static files are typically 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 take a simple example to understand 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. In Solution Explorer, right-click the Wwwroot folder and select add→ New Item.

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

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


1

2

3

4

5

6

7

8

9

10


<!DOCTYPE html>

<html>

<head>

<metacharset="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 the app. The run middleware throws an exception because there is nothing in our application at the moment.

Now there is no middleware in our project to find any files on the file system.

To resolve this issue, go to NuGet Package Manager by right-clicking your project in Solution Explorer and selecting Manage NuGet package.

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

Let's add the Usestaticfiles middleware in 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 Configur Ationbuilder () 10. Addjsonfile ("Appsettings.json"); One Configuration = Builder. Build ();  Public iconfiguration Configuration {get; set;} Called/This method gets the runtime. //Use this method to add services to the container. +/For information Configure your application, +//visit Http://go.microsoft.com/fwlink/?L inkid=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) = {New System.Exception ("Throw Exception"); var msg = Configu ration["message"]; Await the context. Response.writeasync (msg); 33}); +//Entry point for the application. Notoginseng public static void Main (string[] args) = webapplication.run<startup> (args); 38} 39}

Unless you override the option by passing in some different configuration parameters, the static file is considered a request path for a given request. This request path is relative to the file system.

    • If a static file finds a file based on a URL, it returns the file directly without invoking the next block middleware.

    • If no matching file is found, it will continue to execute 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 files, CSS files, or HTML files that you place anywhere under the Wwwroot folder can be used directly as static files in ASP.

    • IIS always has this feature if you want index.html to be your default file.

    • 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 the file to the client.

    • Let's start with 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 an 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    Apps. Usedeveloperexceptionpage ();  6      7    apps. Useruntimeinfopage ();   8    Apps. Usedefaultfiles ();  9    Apps. Usestaticfiles ();    app. Run (Async (context) = {       var msg = configuration["message"]; await the       context. Response.writeasync (msg);    );  15}

    • This middleware will listen for incoming requests, and if the request is the root directory, see if there is a matching default file.

    • You can override this middleware option 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 move your browser to the root 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 place usedefaultfiles after usestaticfiles, you will probably not get the same results.

If you want to use Usedefaultfiles and Usestaticfiles middleware, you can use another middleware Microsoft.aspnet.staticfiles, which is also a nuget package, which is a server middleware. This essentially contains the default files 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    Apps. Usedeveloperexceptionpage ();  6      7    apps. Useruntimeinfopage ();   8    app. Usefileserver ();   9    Apps. Run (Async (context) = {one       var msg = configuration["message"];       await context. Response.writeasync (msg);    ); 14}

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.