コード例 #1
0
    /// <summary>
    /// Adds a middleware to the pipeline that will catch exceptions, log them, and re-execute the request in an alternate pipeline.
    /// The request will not be re-executed if the response has already started.
    /// </summary>
    /// <param name="app"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, ExceptionHandlerOptions options)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }
        if (options == null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        var iOptions = Options.Create(options);

        return(SetExceptionHandlerMiddleware(app, iOptions));
    }
コード例 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors("AllowAll");
            //app.UseSession();


            //  if (!env.IsDevelopment() || ResponseBuilder.isUserException)
            //  {
            //app.UseDeveloperExceptionPage();
            ExceptionHandlerOptions options = new ExceptionHandlerOptions();

            //options.
            app.UseExceptionHandler(options =>
            {
                options.Run(async context =>
                {
                    context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "application/json";
                    var ex = context.Features.Get <IExceptionHandlerFeature>();
                    if (ex != null)
                    {
                        if (!ResponseBuilder.isUserException)
                        {
                            CurrentInstance.IP = context.Connection.RemoteIpAddress.ToString();
                            new PKG_ERROR_LOGS().LogException(CurrentInstance.userID, ex.Error.Message.ToString(), ex.Error.StackTrace.ToString(), context.Request.Path.ToString(), CurrentInstance.IP, context.Request.QueryString.ToString());
                        }
                        var err = "";
                        err     = ResponseBuilder.Error(ex.Error.Message, Configuration["error_text"].ToString(), env.IsDevelopment());
                        ResponseBuilder.isUserException = false;
                        //err = new ResponseBuilder().Error(Configuration["error_text"].ToString());

                        await context.Response.WriteAsync(err).ConfigureAwait(false);
                    }
                });
            });
            //        }


            app.UseHttpsRedirection();

            app.UseRouting();

            var webSocketOptions = new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024
            };

            //webSocketOptions.AllowedOrigins.Add("https://client.com");

            app.UseWebSockets(webSocketOptions);


            app.UseAuthorization();
            app.UseSession();

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

            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/Chat")
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        await new ChatService().GetAndSendMessage(context);
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                    }
                }
                else
                {
                    await next();
                }
            });
        }
コード例 #3
0
        public static IApplicationBuilder UseSidExceptionHandler(this IApplicationBuilder app, ExceptionHandlerOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var optionsWrapper = Microsoft.Extensions.Options.Options.Create(options);

            app.UseMiddleware <ExceptionHandlerMiddleware>(optionsWrapper);

            if (options.ClientExceptionEnabled)
            {
                app.UseMiddleware <ClientExceptionHandlerMiddleware>(optionsWrapper);
            }

            return(app);
        }
コード例 #4
0
 public KraftExceptionHandlerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, ExceptionHandlerOptions options, DiagnosticSource diagnosticSource)
 {
     _Next    = next;
     _Options = options;
     _Logger  = loggerFactory.CreateLogger <ExceptionHandlerMiddleware>();
     if (_Options.ExceptionHandler == null)
     {
         _Options.ExceptionHandler = _Next;
     }
     _ClearCacheHeadersDelegate = ClearCacheHeaders;
     _DiagnosticSource          = diagnosticSource;
 }
コード例 #5
0
        public async Task TestExceptionLogger()
        {
            Mock <IMailSender> emailSenderMock = null;
            int processManualTimes             = 0;

            var hostBuilder = new WebHostBuilder();

            hostBuilder.ConfigureServices(collection =>
            {
                emailSenderMock = new Mock <IMailSender>();
                emailSenderMock.Setup(
                    p => p.SendEmailAsync(It.IsAny <MailMessage>()));
                collection.AddSingleton <IMailSender>(provider => emailSenderMock.Object);

                collection.AddSidExceptionHandler(options =>
                {
                    options.Tos = new List <MailAddress>
                    {
                        new MailAddress {
                            Address = "*****@*****.**"
                        },
                        new MailAddress {
                            Address = "*****@*****.**"
                        }
                    };
                    options.Subject = "Test Error";
                }
                                                  //, provider =>
                                                  //{
                                                  //    var sender = new Mock<IMailSender>();
                                                  //    sender.Setup(
                                                  //        p => p.SendEmailAsync(It.IsAny<MailMessage>()));
                                                  //    return sender.Object;
                                                  //}
                                                  );
            });
            hostBuilder.Configure(app =>
            {
                var options = new ExceptionHandlerOptions
                {
                    SendErrorEnabled = true,
                    ManualProcess    = exception => { processManualTimes++; }
                };


                app.UseSidExceptionHandler(options);
                app.Run(context =>
                {
                    throw new System.Exception("Server Error");
                });
            });

            using (var testServer = new TestServer(hostBuilder))
            {
                var response = await testServer.CreateRequest("/").GetAsync();

                Assert.Equal(500, (int)response.StatusCode);
                var result = JsonConvert.DeserializeObject <ApiErrorResult>(await response.Content.ReadAsStringAsync());
                Assert.NotNull(result);
                Assert.Equal("Server Error", result.Message);

                Assert.Equal(1, processManualTimes);

                emailSenderMock.Verify(
                    p => p.SendEmailAsync(It.IsAny <MailMessage>()), Times.Once);
            }
        }
コード例 #6
0
 public ExceptionHandler(IOptions <ExceptionHandlerOptions> handlerOptions, ILoggerFactory loggerFactory)
 {
     _loggerFactory  = loggerFactory;
     _handlerOptions = handlerOptions.Value;
 }