private void AppendException(StringBuilder text, Exception e)
        {
            var exceptionDetails = _exceptionDetailsProvider.GetDetails(e);

            foreach (var exceptionDetail in exceptionDetails)
            {
                AppendExceptionDetail(text, exceptionDetail);
            }

            text.AppendLine();
        }
Beispiel #2
0
        private Task DisplayRuntimeException(HttpContext context, Exception ex)
        {
            var endpoint = context.GetEndpoint();

            EndpointModel?endpointModel = null;

            if (endpoint != null)
            {
                endpointModel             = new EndpointModel();
                endpointModel.DisplayName = endpoint.DisplayName;

                if (endpoint is RouteEndpoint routeEndpoint)
                {
                    endpointModel.RoutePattern = routeEndpoint.RoutePattern.RawText;
                    endpointModel.Order        = routeEndpoint.Order;

                    var httpMethods = endpoint.Metadata.GetMetadata <IHttpMethodMetadata>()?.HttpMethods;
                    if (httpMethods != null)
                    {
                        endpointModel.HttpMethods = string.Join(", ", httpMethods);
                    }
                }
            }

            var request = context.Request;
            var title   = Resources.ErrorPageHtml_Title;

            if (ex is BadHttpRequestException badHttpRequestException)
            {
                var badRequestReasonPhrase = WebUtilities.ReasonPhrases.GetReasonPhrase(badHttpRequestException.StatusCode);

                if (!string.IsNullOrEmpty(badRequestReasonPhrase))
                {
                    title = badRequestReasonPhrase;
                }
            }

            var model = new ErrorPageModel
            {
                Options      = _options,
                ErrorDetails = _exceptionDetailsProvider.GetDetails(ex),
                Query        = request.Query,
                Cookies      = request.Cookies,
                Headers      = request.Headers,
                RouteValues  = request.RouteValues,
                Endpoint     = endpointModel,
                Title        = title,
            };

            var errorPage = new ErrorPage(model);

            return(errorPage.ExecuteAsync(context));
        }
 public async Task <string> Ha()
 {
     try
     {
         throw new ArgumentException("测试一场");
     }
     catch (Exception e)
     {
         var ex = _exceptionDetailsProvider.GetDetails(e);
         return(await View(ex));
     }
 }
        private RequestDelegate BuildErrorPageApplication(Exception exception)
        {
            if (exception is TargetInvocationException tae)
            {
                exception = tae.InnerException;
            }

            var showDetailedErrors = HostingEnvironment.IsDevelopment() || Options.WebHostOptions.DetailedErrors;

            var model = new ErrorPageModel
            {
                RuntimeDisplayName = RuntimeInformation.FrameworkDescription
            };
            var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).Assembly;
            var assemblyVersion       = new AssemblyName(systemRuntimeAssembly.FullName).Version.ToString();
            var clrVersion            = assemblyVersion;

            model.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToString();
            var currentAssembly = typeof(ErrorPage).Assembly;

            model.CurrentAssemblyVesion = currentAssembly
                                          .GetCustomAttribute <AssemblyInformationalVersionAttribute>()
                                          .InformationalVersion;
            model.ClrVersion = clrVersion;
            model.OperatingSystemDescription = RuntimeInformation.OSDescription;
            model.ShowRuntimeDetails         = showDetailedErrors;

            if (showDetailedErrors)
            {
                var exceptionDetailProvider = new ExceptionDetailsProvider(
                    HostingEnvironment.ContentRootFileProvider,
                    Logger,
                    sourceCodeLineCount: 6);

                model.ErrorDetails = exceptionDetailProvider.GetDetails(exception);
            }
            else
            {
                model.ErrorDetails = Array.Empty <ExceptionDetails>();
            }

            var errorPage = new ErrorPage(model);

            return(context =>
            {
                context.Response.StatusCode = 500;
                context.Response.Headers[HeaderNames.CacheControl] = "no-cache,no-store";
                context.Response.Headers[HeaderNames.Pragma] = "no-cache";
                context.Response.ContentType = "text/html; charset=utf-8";
                return errorPage.ExecuteAsync(context);
            });
        }
        private Task DisplayRuntimeException(HttpContext context, Exception ex)
        {
            var request = context.Request;

            var model = new ErrorPageModel
            {
                Options      = _options,
                ErrorDetails = _exceptionDetailsProvider.GetDetails(ex),
                Query        = request.Query,
                Cookies      = request.Cookies,
                Headers      = request.Headers
            };

            var errorPage = new ErrorPage(model);

            return(errorPage.ExecuteAsync(context));
        }
Beispiel #6
0
        private Task DisplayRuntimeException(HttpContext context, Exception ex)
        {
            var endpoint = context.Features.Get <IEndpointFeature>()?.Endpoint;

            EndpointModel endpointModel = null;

            if (endpoint != null)
            {
                endpointModel             = new EndpointModel();
                endpointModel.DisplayName = endpoint.DisplayName;

                if (endpoint is RouteEndpoint routeEndpoint)
                {
                    endpointModel.RoutePattern = routeEndpoint.RoutePattern.RawText;
                    endpointModel.Order        = routeEndpoint.Order;

                    var httpMethods = endpoint.Metadata.GetMetadata <IHttpMethodMetadata>()?.HttpMethods;
                    if (httpMethods != null)
                    {
                        endpointModel.HttpMethods = string.Join(", ", httpMethods);
                    }
                }
            }

            var request = context.Request;

            var model = new ErrorPageModel
            {
                Options      = _options,
                ErrorDetails = _exceptionDetailsProvider.GetDetails(ex),
                Query        = request.Query,
                Cookies      = request.Cookies,
                Headers      = request.Headers,
                RouteValues  = request.RouteValues,
                Endpoint     = endpointModel
            };

            var errorPage = new ErrorPage(model);

            return(errorPage.ExecuteAsync(context));
        }
        public static ErrorPageModel CreateErrorPageModel(
            IFileProvider contentRootFileProvider,
            ILogger?logger,
            bool showDetailedErrors,
            Exception exception)
        {
            var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).Assembly;
            var assemblyVersion       = new AssemblyName(systemRuntimeAssembly.FullName !).Version?.ToString() ?? string.Empty;
            var clrVersion            = assemblyVersion;
            var currentAssembly       = typeof(ErrorPage).Assembly;
            var currentAssemblyVesion = currentAssembly
                                        .GetCustomAttribute <AssemblyInformationalVersionAttribute>() !
                                        .InformationalVersion;

            IEnumerable <ExceptionDetails> errorDetails;

            if (showDetailedErrors)
            {
                var exceptionDetailProvider = new ExceptionDetailsProvider(
                    contentRootFileProvider,
                    logger,
                    sourceCodeLineCount: 6);

                errorDetails = exceptionDetailProvider.GetDetails(exception);
            }
            else
            {
                errorDetails = Array.Empty <ExceptionDetails>();
            }

            var model = new ErrorPageModel(
                errorDetails,
                showDetailedErrors,
                RuntimeInformation.FrameworkDescription,
                RuntimeInformation.ProcessArchitecture.ToString(),
                clrVersion,
                currentAssemblyVesion,
                RuntimeInformation.OSDescription);

            return(model);
        }
Beispiel #8
0
        private RequestDelegate BuildApplication()
        {
            try
            {
                _applicationServicesException?.Throw();
                EnsureServer();

                var builderFactory = _applicationServices.GetRequiredService <IApplicationBuilderFactory>();
                var builder        = builderFactory.CreateBuilder(Server.Features);
                builder.ApplicationServices = _applicationServices;

                var startupFilters = _applicationServices.GetService <IEnumerable <IStartupFilter> >();
                Action <IApplicationBuilder> configure = _startup.Configure;
                foreach (var filter in startupFilters.Reverse())
                {
                    configure = filter.Configure(configure);
                }

                configure(builder);

                return(builder.Build());
            }
            catch (Exception ex)
            {
                if (!_options.SuppressStatusMessages)
                {
                    // Write errors to standard out so they can be retrieved when not in development mode.
                    Console.WriteLine("Application startup exception: " + ex.ToString());
                }
                var logger = _applicationServices.GetRequiredService <ILogger <WebHost> >();
                logger.ApplicationError(ex);

                if (!_options.CaptureStartupErrors)
                {
                    throw;
                }

                EnsureServer();

                // Generate an HTML error page.
                var hostingEnv         = _applicationServices.GetRequiredService <IHostingEnvironment>();
                var showDetailedErrors = hostingEnv.IsDevelopment() || _options.DetailedErrors;

                var model = new ErrorPageModel
                {
                    RuntimeDisplayName = RuntimeInformation.FrameworkDescription
                };
                var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).GetTypeInfo().Assembly;
                var assemblyVersion       = new AssemblyName(systemRuntimeAssembly.FullName).Version.ToString();
                var clrVersion            = assemblyVersion;
                model.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToString();
                var currentAssembly = typeof(ErrorPage).GetTypeInfo().Assembly;
                model.CurrentAssemblyVesion = currentAssembly
                                              .GetCustomAttribute <AssemblyInformationalVersionAttribute>()
                                              .InformationalVersion;
                model.ClrVersion = clrVersion;
                model.OperatingSystemDescription = RuntimeInformation.OSDescription;

                if (showDetailedErrors)
                {
                    var exceptionDetailProvider = new ExceptionDetailsProvider(
                        hostingEnv.ContentRootFileProvider,
                        sourceCodeLineCount: 6);

                    model.ErrorDetails = exceptionDetailProvider.GetDetails(ex);
                }
                else
                {
                    model.ErrorDetails = new ExceptionDetails[0];
                }

                var errorPage = new ErrorPage(model);
                return(context =>
                {
                    context.Response.StatusCode = 500;
                    context.Response.Headers["Cache-Control"] = "no-cache";
                    return errorPage.ExecuteAsync(context);
                });
            }
        }
Beispiel #9
0
    /// <summary>
    /// Startup hooks are pieces of code that will run before a users program main executes
    /// See: https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/host-startup-hook.md
    /// </summary>
    public static void Initialize()
    {
        if (!NativeMethods.IsAspNetCoreModuleLoaded())
        {
            // This means someone set the startup hook for Microsoft.AspNetCore.Server.IIS
            // but are not running inprocess. Return at this point.
            return;
        }

        var detailedErrors         = Environment.GetEnvironmentVariable("ASPNETCORE_DETAILEDERRORS");
        var enableStartupErrorPage = detailedErrors?.Equals("1", StringComparison.OrdinalIgnoreCase) ?? false;

        enableStartupErrorPage |= detailedErrors?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false;

        var aspnetCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

        enableStartupErrorPage |= aspnetCoreEnvironment?.Equals("Development", StringComparison.OrdinalIgnoreCase) ?? false;

        var dotnetEnvironment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");

        enableStartupErrorPage |= dotnetEnvironment?.Equals("Development", StringComparison.OrdinalIgnoreCase) ?? false;

        if (!enableStartupErrorPage)
        {
            // Not running in development or detailed errors aren't enabled
            return;
        }

        AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
        {
            var exception = (Exception)eventArgs.ExceptionObject;

            // Get the content root from IIS.
            var iisConfigData = NativeMethods.HttpGetApplicationProperties();
            var contentRoot   = iisConfigData.pwzFullApplicationPath.TrimEnd(Path.DirectorySeparatorChar);

            var model = new ErrorPageModel
            {
                RuntimeDisplayName = RuntimeInformation.FrameworkDescription
            };

            var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).Assembly;
            var assemblyVersion       = new AssemblyName(systemRuntimeAssembly.FullName).Version.ToString();
            var clrVersion            = assemblyVersion;
            model.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToString();
            var currentAssembly = typeof(ErrorPage).Assembly;
            model.CurrentAssemblyVesion = currentAssembly
                                          .GetCustomAttribute <AssemblyInformationalVersionAttribute>()
                                          .InformationalVersion;
            model.ClrVersion = clrVersion;
            model.OperatingSystemDescription = RuntimeInformation.OSDescription;

            var exceptionDetailProvider = new ExceptionDetailsProvider(
                new PhysicalFileProvider(contentRoot),
                logger: null,
                sourceCodeLineCount: 6);

            // The startup hook is only present when detailed errors are allowed, so
            // we can turn on all the details.
            model.ErrorDetails       = exceptionDetailProvider.GetDetails(exception);
            model.ShowRuntimeDetails = true;

            var errorPage = new ErrorPage(model);

            var stream = new MemoryStream();

            // Never will go async because we are writing to a memory stream.
            errorPage.ExecuteAsync(stream).GetAwaiter().GetResult();

            // Get the raw content and set the error page.
            stream.Position = 0;
            var content = stream.ToArray();

            NativeMethods.HttpSetStartupErrorPageContent(content);
        };
    }
Beispiel #10
0
        private RequestDelegate BuildApplication()
        {
            try
            {
                EnsureApplicationServices();
                EnsureServer();

                var builderFactory = _applicationServices.GetRequiredService <IApplicationBuilderFactory>();
                var builder        = builderFactory.CreateBuilder(Server.Features);
                builder.ApplicationServices = _applicationServices;

                var startupFilters = _applicationServices.GetService <IEnumerable <IStartupFilter> >();
                Action <IApplicationBuilder> configure = _startup.Configure;
                foreach (var filter in startupFilters.Reverse())
                {
                    configure = filter.Configure(configure);
                }

                configure(builder);

                return(builder.Build());
            }
            catch (Exception ex) when(_options.CaptureStartupErrors)
            {
                // EnsureApplicationServices may have failed due to a missing or throwing Startup class.
                if (_applicationServices == null)
                {
                    _applicationServices = _applicationServiceCollection.BuildServiceProvider();
                }

                EnsureServer();

                // Write errors to standard out so they can be retrieved when not in development mode.
                Console.Out.WriteLine("Application startup exception: " + ex.ToString());
                var logger = _applicationServices.GetRequiredService <ILogger <WebHost> >();

                logger.ApplicationError(ex);

                // Generate an HTML error page.
                var hostingEnv         = _applicationServices.GetRequiredService <IHostingEnvironment>();
                var showDetailedErrors = hostingEnv.IsDevelopment() || _options.DetailedErrors;

                var model       = new ErrorPageModel();
                var runtimeType = Microsoft.Extensions.Internal.RuntimeEnvironment.RuntimeType;

                model.RuntimeDisplayName = (runtimeType == "CoreCLR") ? ".NET Core" : runtimeType == "CLR" ? ".NET Framework" : "Mono";
#if NETSTANDARD1_3 || NETSTANDARD1_5
                var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).GetTypeInfo().Assembly;
                var assemblyVersion       = new AssemblyName(systemRuntimeAssembly.FullName).Version.ToString();
                var clrVersion            = assemblyVersion;
#else
                var clrVersion = Environment.Version.ToString();
#endif
                model.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToString();
                var currentAssembly = typeof(ErrorPage).GetTypeInfo().Assembly;
                model.CurrentAssemblyVesion = currentAssembly
                                              .GetCustomAttribute <AssemblyInformationalVersionAttribute>()
                                              .InformationalVersion;
                model.ClrVersion = clrVersion;
                model.OperatingSystemDescription = RuntimeInformation.OSDescription;

                if (showDetailedErrors)
                {
                    var exceptionDetailProvider = new ExceptionDetailsProvider(
                        hostingEnv.ContentRootFileProvider,
                        sourceCodeLineCount: 6);

                    model.ErrorDetails = exceptionDetailProvider.GetDetails(ex);
                }
                else
                {
                    model.ErrorDetails = new ExceptionDetails[0];
                }

                var errorPage = new ErrorPage(model);
                return(context =>
                {
                    context.Response.StatusCode = 500;
                    context.Response.Headers["Cache-Control"] = "no-cache";
                    return errorPage.ExecuteAsync(context);
                });
            }
        }