>  기사  >  백엔드 개발  >  ASP.NET Core 예제 자습서: 예외 처리 및 정적 파일 자습서

ASP.NET Core 예제 자습서: 예외 처리 및 정적 파일 자습서

零下一度
零下一度원래의
2017-06-16 10:08:101374검색
<h1 class="h1">Asp.Net Core-Exception Handling</h1> <ol class=" list-paddingleft-2"><li><p>Asp.Net Core-Exception Handling</p></li></ol> <p>이 장에서는 예외 및 오류 처리에 대해 설명합니다. ASP.NET Core 애플리케이션에서 오류가 발생하면 다양한 방법으로 오류를 처리할 수 있습니다. 오류를 처리하는 데 도움이 되는 미들웨어를 추가하여 예외를 처리하는 방법을 살펴보겠습니다. </p> <p>오류를 시뮬레이션하려면 애플리케이션으로 이동하여 실행하고 예외가 발생하면 프로그램이 어떻게 작동하는지 살펴보겠습니다. </p> <p class="cnblogs_code"><br></p> <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> <p></p> <p></p> <p></p> <p>매우 일반적인 예외 메시지가 표시됩니다. Startup.cs 페이지를 저장하고 애플리케이션을 실행합니다. </p> <p><img src="https://img.php.cn/upload/article/000/001/506/470d228a9709dbe93d976747550661ed-0.jpg" alt=""></p> <p> 이 리소스를 로드하지 못한 것을 볼 수 있습니다. HTTP 500 오류, 내부 서버 오류가 발생했고 해당 페이지는 별로 도움이 되지 않았습니다. 일부 예외 정보를 얻는 것이 편리할 수 있습니다. </p> <p>다른 미들웨어 UseDeveloperExceptionPage를 추가해 보겠습니다. </p> <p class="cnblogs_code"><br></p> <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> <p> </p> <p> </p> <p>이 미들웨어는 다른 미들웨어와 약간 다릅니다. 다른 미들웨어는 일반적으로 들어오는 요청을 듣고 요청에 응답합니다. </p> <p>UseDeveloperExceptionPage는 나중에 파이프라인에서 들어오는 요청에 어떤 일이 일어나는지 별로 신경 쓰지 않습니다. </p> <p>다음 미들웨어를 호출한 다음 파이프라인에 예외가 있는지 확인하기 위해 기다립니다. 예외가 있으면 이 미들웨어는 예외에 대한 오류 페이지를 제공합니다. </p> <p>이제 다시 애플리케이션을 실행해 보겠습니다. 그러면 아래 스크린샷과 같은 출력이 생성됩니다. </p> <p><img src="https://img.php.cn/upload/article/000/001/506/470d228a9709dbe93d976747550661ed-1.jpg" alt=""></p> <p>이제 프로그램에서 예외가 발생하면 보고 싶은 몇 가지 예외 정보가 페이지에 표시됩니다. 스택 추적도 얻을 수 있습니다. 여기에서는 Startup.cs의 37번째 줄에서 처리되지 않은 예외가 발생했음을 확인할 수 있습니다. </p> <p>이 모든 예외 정보는 개발자에게 매우 유용합니다. 실제로 개발자가 애플리케이션을 실행할 때만 이러한 예외 메시지가 표시되기를 원할 수도 있습니다. </p> <p> </p> <h1 class="h1">Asp.Net Core 정적 파일 </h1> <ol class=" list-paddingleft-2"> <li><p>Asp.Net Core 정적 파일 </p></li> <li><p>Case </p></li> </ol> <p>이 장에서는 파일 사용 방법을 알아봅니다. 거의 모든 웹 애플리케이션에는 중요한 기능, 즉 파일 시스템에서 파일(정적 파일)을 제공하는 기능이 필요합니다. </p> <ul class=" list-paddingleft-2"> <li><p>JavaScript 파일, 이미지, CSS 파일 등과 같은 정적 파일인 Asp.Net Core 애플리케이션을 고객에게 직접 제공할 수 있습니다. </p></li> <li><p>정적 파일은 일반적으로 웹 루트(wwwroot) 폴더에 있습니다. </p></li> <li><p>기본적으로 이곳은 파일 시스템에서 직접 파일을 제공할 수 있는 유일한 장소입니다. </p></li> </ul> <p> </p> <hr> <h2>Case </h2> <p>이제 애플리케이션에서 이러한 정적 파일을 제공하는 방법을 이해하기 위해 간단한 예를 살펴보겠습니다. </p> <p>여기서 웹 루트(wwwroot) 폴더에 있는 FirstAppDemo 애플리케이션에 간단한 HTML 파일을 추가하려고 합니다. 솔루션 탐색기에서 wwwroot 폴더를 마우스 오른쪽 버튼으로 클릭하고 추가 → 새 항목을 선택합니다. </p> <p><img src="https://img.php.cn/upload/article/000/001/506/470d228a9709dbe93d976747550661ed-2.jpg" alt=""></p> <p>가운데 창에서 HTML 페이지를 선택하고 이름을 index.html로 지정하고 추가 버튼을 클릭하세요. </p> <p><img src="https://img.php.cn/upload/article/000/001/506/470d228a9709dbe93d976747550661ed-3.jpg" alt=""></p> <p>간단한 index.html 파일이 표시됩니다. 아래와 같이 간단한 텍스트와 제목을 추가해 보겠습니다. </p> <p class="syntaxhighlighter html"><br></p> <table border="0"><tbody><tr class="firstRow"> <td class="gutter"> <p class="line number1 index0 alt2">1</p> <p class="line number2 index1 alt1">2</p> <p class="line number3 index2 alt2">3</p> <p class="line number4 index3 alt1">4</p> <p class="line number5 index4 alt2">5</p> <p class="line number6 index5 alt1">6</p> <p class="line number7 index6 alt2">7</p> <p class="line number8 index7 alt1">8</p> <p class="line number9 index8 alt2">9</p> <p class="line number10 index9 alt1">10 </p> </td> <td class="code"> <p class="container"><br></p> <p class="line number1 index0 alt2"><code class="html plain"><!DOCTYPE html> </code><code class="html plain"><!DOCTYPE html> </code></p> <p class="line number2 index1 alt1"><code class="html plain"><</code><code class="html keyword">html</code><code class="html plain">> </code></p> <p class="line number3 index2 alt2"><code class="html spaces">   </code><code class="html plain"><</code><code class="html keyword">head</code><code class="html plain">> </code></p> <code class="html plain"><</code><code class="html 키워드">html</code><code class="html plain">> </code>🎜🎜<code class="html space"> </code><code class="html plain"><</code><code class="html 키워드">head< /code><code class="html plain">> </code>🎜<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> </td> </tr></tbody></table> <p>当您运行应用程序并在浏览器中输入index.html时,您将看到app.Run中间件将抛出一个异常,因为目前在我们的应用程序中什么都没有。</p> <p><img src="https://img.php.cn/upload/article/000/001/506/315d89c3796749d419a682e7ec51873a-4.jpg" alt=""></p> <p>现在我们的项目中没有中间件会去找文件系统上的任何文件。</p> <p>为了解决这个问题,通过在解决方案资源管理器中右键单击您的项目并选择管理NuGet包进入到NuGet包管理器。</p> <p><img src="https://img.php.cn/upload/article/000/001/506/315d89c3796749d419a682e7ec51873a-5.jpg" alt=""></p> <p>搜索 Microsoft.AspNet.StaticFiles,会找到静态文件中间件。让我们安装此 nuget 程序包,现在我们可以在Configure方法中注册中间件。</p> <p>让我们在下面的程序中所示的Configure方法中添加 UseStaticFiles 中间件。</p> <p class="cnblogs_code"><br></p> <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> <p>除非你通过传入一些不同的配置参数来覆盖选项,否则静态文件会对于一个给定的请求看作是请求路径。这个请求路径是相对于文件系统。</p> <ul class=" list-paddingleft-2"> <li><p>如果静态文件根据url找到一个文件,它将直接返回该文件,而不调用下一个块中间件。</p></li> <li><p>如果没有找到匹配的文件,那么它会继续执行下一个块中间件。</p></li> </ul> <p>让我们保存Startup.cs文件并刷新浏览器。</p> <p><img src="https://img.php.cn/upload/article/000/001/506/315d89c3796749d419a682e7ec51873a-6.jpg" 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> <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> <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="https://img.php.cn/upload/article/000/001/506/315d89c3796749d419a682e7ec51873a-7.jpg" alt=""></p> <p>你现在可以看到index.html是默认文件。你安装中间件的顺序是很重要的,因为如果你将UseDefaultFiles放置在UseStaticFiles之后,你将可能不会得到相同的结果。</p> <p>如果你想要使用UseDefaultFiles和UseStaticFiles中间件,你可以使用另一个中间件Microsoft.aspnet.staticfiles,它也是NuGet包,它是一个服务器中间件。这本质上是以正确的顺序包含了默认文件和静态文件。</p> <p class="cnblogs_code"><br></p> <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> <p> </p> <p> </p> <p>让我们再一次保存 Startup.cs 文件。一旦你刷新浏览器,你将看到相同的结果,如下面的屏幕快照所示。</p> <p><img src="https://img.php.cn/upload/article/000/001/506/b33e085c39ca50d6c54911a15965303c-8.jpg" alt=""></p>

위 내용은 ASP.NET Core 예제 자습서: 예외 처리 및 정적 파일 자습서의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.