示例#1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    // get diagnostic information about the error
                    var exceptionHandlerPathFeature =
                        context.Features.Get <IExceptionHandlerPathFeature>();

                    // get the exception that was thrown from endpoint
                    var exceptionThrown = exceptionHandlerPathFeature.Error;

                    // return a status code and generic json message
                    context.Response.StatusCode  = FailureResult.GetStatusCode(exceptionThrown);
                    context.Response.ContentType = "application/json";

                    var json = JsonConvert.SerializeObject(new FailureResult(exceptionThrown));
                    await context.Response.WriteAsync(json);

                    // log the error
                    var logger = errorApp.ApplicationServices.GetService <ILogger <Program> >();
                    logger.LogError(_errorEventId++, exceptionThrown, $"exception caught in UseExceptionHandler middleware, see exception for details");
                });
            });

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Urban Engine API v1");
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }