Esempio n. 1
0
        public async Task InvokeErrorHandler_ExceptionTest()
        {
            var applicationInsightsMock = new ApplicationInsightsSettings()
            {
                InstrumentationKey = "118047f1-b165-4bff-9471-e87fd3fe167c"
            };

            _applicationInsightsMock.Setup(x => x.Value)
            .Returns(applicationInsightsMock);

            _webHostEnvironmentMock.Setup(x => x.EnvironmentName)
            .Returns("Development");

            var httpContext             = new DefaultHttpContext().Request.HttpContext;
            var exceptionHandlerFeature = new ExceptionHandlerFeature()
            {
                Error = new Exception("Mock error exception")
            };

            httpContext.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);

            var errorHandlerMiddleware = new ErrorHandlerMiddleware(_applicationInsightsMock.Object, _webHostEnvironmentMock.Object);
            await errorHandlerMiddleware.Invoke(httpContext);

            Assert.NotNull(errorHandlerMiddleware);
        }
        public async Task ShouldLogHouseholdException()
        {
            // Arrange
            string expectedFormattedMsg = "test";
            string extectedErrorMsg     = "test";
            var    logger  = new Mock <ILogger <ErrorHandlerMiddleware> >();
            var    context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            var actual = new ErrorHandlerMiddleware(next: (innerHttpContext) =>
            {
                throw new HouseholdException(extectedErrorMsg);
            }, logger: logger.Object);

            // Act
            await actual.Invoke(context);

            // Assert
            logger.Verify(e => e.Log(
                              LogLevel.Error,
                              It.IsAny <EventId>(),
                              It.Is <FormattedLogValues>(a => a.ToString().Equals(expectedFormattedMsg)),
                              It.Is <Exception>(a => a.Message.Equals(extectedErrorMsg)),
                              It.IsAny <Func <object, Exception, string> >()),
                          Times.Once
                          );
        }
        public async Task ShouldCreateResponseForException()
        {
            // Arrange
            string expectedErrorCode = "error";
            string extectedErrorMsg  = "test";
            var    logger            = new Mock <ILogger <ErrorHandlerMiddleware> >();
            var    context           = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            var actual = new ErrorHandlerMiddleware(next: (innerHttpContext) =>
            {
                throw new Exception(extectedErrorMsg);
            }, logger: logger.Object);

            // Act
            await actual.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader      = new StreamReader(context.Response.Body);
            var streamText  = reader.ReadToEnd();
            var objResponse = JsonConvert.DeserializeObject <dynamic>(streamText);

            // Assert
            Assert.IsTrue(context.Response.StatusCode == (int)HttpStatusCode.BadRequest);
            Assert.IsTrue(context.Response.ContentType == "application/json");
            Assert.IsTrue(objResponse != null);
            Assert.IsTrue(objResponse.code == expectedErrorCode);
            Assert.IsTrue(objResponse.message == extectedErrorMsg);
        }
        public async Task TestHandledExceptionHandler()
        {
            middleware = new ErrorHandlerMiddleware(
                next: (innerHttpContext) => Task.FromException(new SimpliPassException("Test Exception")), logger.Object);

            await middleware.Invoke(httpContext);

            int statusCode = httpContext.Response.StatusCode;

            Assert.AreEqual(statusCode, (int)HttpStatusCode.BadRequest);
        }
        public async Task InvokeErrorHandlerMiddlewareWhenNotExistExceptionTest()
        {
            _webHostEnvironmentMock.Setup(setup => setup.EnvironmentName)
            .Returns("Development");

            var httpContext = new DefaultHttpContext().Request.HttpContext;

            var middleware = new ErrorHandlerMiddleware(_webHostEnvironmentMock.Object);
            await middleware.Invoke(httpContext);

            Assert.NotNull(middleware);
        }
Esempio n. 6
0
        public async Task InvokeErrorHandler_NotExceptionTestAsync()
        {
            var applicationInsightsMock = new ApplicationInsightsSettings("118047f1-b165-4bff-9471-e87fd3fe167c");

            _applicationInsightsMock.Setup(x => x.Value)
            .Returns(applicationInsightsMock);

            _hostingEnvironmentMock.Setup(x => x.EnvironmentName)
            .Returns("Development");

            var httpContext = new DefaultHttpContext().Request.HttpContext;

            var errorHandlerMiddleware = new ErrorHandlerMiddleware(_applicationInsightsMock.Object, _hostingEnvironmentMock.Object);
            await errorHandlerMiddleware.Invoke(httpContext);

            Assert.NotNull(errorHandlerMiddleware);
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                opt.SerializerSettings.ContractResolver      = new DefaultContractResolver();
            });
            // Configure HttpContextAccessor that can get http request & response context in filter.
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddCors();

            // Configure Jwt token generator information
            services.Configure <JwtTokenConfig>(Configuration.GetSection("JwtSignatureInfo"));
            services.Configure <StaticFilePathResolver>(Configuration.GetSection("StaticFilesStorePath"));
            EnsureStaticFilePathValid(services);
            services.Configure <RabbitMQConfiguration>(Configuration.GetSection("RabbitMQServer"));
            services.AddSingleton <JwtManager>();
            services.AddSingleton <TokenManager>();


            // Configure databases connection.
            services.Configure <MongoClientConfiguration>(Configuration.GetSection("Mongo"));
            services.AddMongoDB();
            services.AddScoped <MongoContext>();
            services.AddDbContext <OtokatariContext>(cfg => cfg.UseMySQL(Configuration["MySQLConnection"]));

            // Configure RSA utils
            services.Configure <RSAKeyFiles>(Configuration.GetSection("RsaKeys"));
            services.AddRsaUtils();

            // Configure services in the project.

            services.AddSingleton <IdWorker>();
            services.AddAllServices <IOtokatariService>();
            services.AddAllServices <IOtokatariDbOperator>();
            services.AddSingleton <AnalyzerQueue>();

            ErrorHandlerMiddleware.Builder()
            .AddErrorStatusCode <FormatException>(-1002)
            .ConfigureErrorHandler(services);


            // Configure access controller.
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//配置JWT服务
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    ValidAudience            = Configuration["JwtSignatureInfo:Audience"],
                    ValidIssuer      = Configuration["JwtSignatureInfo:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSignatureInfo:SecurityKey"]))   //拿到SecurityKey
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        //Give client some tips in header when request token is expired.
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            // Configure redis cache to store revoked tokens.
            services.AddDistributedRedisCache(r =>
            {
                r.Configuration = Configuration["Redis:ConnectionString"];
                r.InstanceName  = "token";
            });
        }
 public ErrorHandlerMiddlewareTests()
 {
     _mocker     = new AutoMocker();
     _middleware = _mocker.CreateInstance <ErrorHandlerMiddleware>();
 }