Ejemplo n.º 1
0
        public async Task Invoke(HttpContext context)
        {
            using (RequestServicesContainer.EnsureRequestServices(context, _services))
            {
                AuthenticationHandler <TOptions> handler = CreateHandler();
                await handler.Initialize(Options, context);

                try
                {
                    if (!await handler.InvokeAsync())
                    {
                        await _next(context);
                    }
                }
                catch (Exception)
                {
                    try
                    {
                        handler.Faulted = true;
                        await handler.TeardownAsync();
                    }
                    catch (Exception)
                    {
                        // Don't mask the original exception
                    }
                    throw;
                }
                await handler.TeardownAsync();
            }
        }
Ejemplo n.º 2
0
        public async Task Invoke(HttpContext httpContext)
        {
            using (RequestServicesContainer.EnsureRequestServices(httpContext, Services))
            {
                EnsureLogger(httpContext);
                using (_logger.BeginScope("RouterMiddleware.Invoke"))
                {
                    var context = new RouteContext(httpContext);
                    context.RouteData.Routers.Add(Router);

                    await Router.RouteAsync(context);

                    if (_logger.IsEnabled(TraceType.Verbose))
                    {
                        _logger.WriteValues(new RouterMiddlewareInvokeValues()
                        {
                            Handled = context.IsHandled
                        });
                    }

                    if (!context.IsHandled)
                    {
                        await Next.Invoke(httpContext);
                    }
                }
            }
        }
        public async Task Invoke(HttpContext context)
        {
            using (RequestServicesContainer.EnsureRequestServices(context, _services))
            {
                AuthenticationHandler <TOptions> handler = CreateHandler();
                await handler.Initialize(Options, context);

                if (!await handler.InvokeAsync())
                {
                    await _next(context);
                }
                await handler.TeardownAsync();
            }
        }
        public virtual async Task Invoke([NotNull] HttpContext context)
        {
            Check.NotNull(context, "context");

            if (context.Request.Path.Equals(_options.Path))
            {
                _logger.WriteVerbose(Strings.FormatMigrationsEndPointMiddleware_RequestPathMatched(context.Request.Path));

                using (RequestServicesContainer.EnsureRequestServices(context, _serviceProvider))
                {
                    var db = await GetDbContext(context, _logger).WithCurrentCulture();

                    if (db != null)
                    {
                        try
                        {
                            _logger.WriteVerbose(Strings.FormatMigrationsEndPointMiddleware_ApplyingMigrations(db.GetType().FullName));

                            db.Database.AsRelational().ApplyMigrations();

                            context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                            context.Response.Headers.Add("Pragma", new[] { "no-cache" });
                            context.Response.Headers.Add("Cache-Control", new[] { "no-cache" });

                            _logger.WriteVerbose(Strings.FormatMigrationsEndPointMiddleware_Applied(db.GetType().FullName));
                        }
                        catch (Exception ex)
                        {
                            var message = Strings.FormatMigrationsEndPointMiddleware_Exception(db.GetType().FullName);
                            _logger.WriteError(message);
                            throw new InvalidOperationException(message, ex);
                        }
                    }
                }
            }
            else
            {
                await _next(context).WithCurrentCulture();
            }
        }
Ejemplo n.º 5
0
        public void EnsureRequestServicesSetsRequestServices(bool initializeApplicationServices)
        {
            var baseServiceProvider = new ServiceCollection()
                                      .Add(HostingServices.GetDefaultServices())
                                      .BuildServiceProvider();
            var builder = new ApplicationBuilder(baseServiceProvider);

            bool foundRequestServicesBefore = false;

            builder.Use(next => async c =>
            {
                foundRequestServicesBefore = c.RequestServices != null;
                await next.Invoke(c);
            });
            builder.Use(next => async c =>
            {
                using (var container = RequestServicesContainer.EnsureRequestServices(c, baseServiceProvider))
                {
                    await next.Invoke(c);
                }
            });
            bool foundRequestServicesAfter = false;

            builder.Use(next => async c =>
            {
                foundRequestServicesAfter = c.RequestServices != null;
                await next.Invoke(c);
            });

            var context = new DefaultHttpContext();

            if (initializeApplicationServices)
            {
                context.ApplicationServices = baseServiceProvider;
            }
            builder.Build().Invoke(context);
            Assert.False(foundRequestServicesBefore);
            Assert.True(foundRequestServicesAfter);
        }
        public virtual async Task Invoke([NotNull] HttpContext context)
        {
            Check.NotNull(context, "context");

            try
            {
#if !ASPNETCORE50
                // TODO This probably isn't the correct place for this workaround, it
                //      needs to be called before anything is written to CallContext
                // http://msdn.microsoft.com/en-us/library/dn458353(v=vs.110).aspx
                System.Configuration.ConfigurationManager.GetSection("system.xml/xmlReader");
#endif
                _loggerProvider.Logger.StartLoggingForCurrentCallContext();

                await _next(context).WithCurrentCulture();
            }
            catch (Exception ex)
            {
                try
                {
                    if (_loggerProvider.Logger.LastError.IsErrorLogged &&
                        _loggerProvider.Logger.LastError.Exception == ex)
                    {
                        using (RequestServicesContainer.EnsureRequestServices(context, _serviceProvider))
                        {
                            var dbContextType = _loggerProvider.Logger.LastError.ContextType;
                            var dbContext     = (DbContext)context.RequestServices.GetService(dbContextType);
                            if (dbContext == null)
                            {
                                _logger.WriteError(Strings.FormatDatabaseErrorPageMiddleware_ContextNotRegistered(dbContextType.FullName));
                            }
                            else
                            {
                                if (dbContext.Database is RelationalDatabase)
                                {
                                    var databaseExists = dbContext.Database.AsRelational().Exists();

                                    var databaseInternals = (IMigrationsEnabledDatabaseInternals)dbContext.Database;
                                    var migrator          = databaseInternals.Migrator;

                                    var pendingMigrations = migrator.GetPendingMigrations().Select(m => m.GetMigrationId());

                                    var pendingModelChanges = true;
                                    var snapshot            = migrator.MigrationAssembly.ModelSnapshot;
                                    if (snapshot != null)
                                    {
                                        pendingModelChanges = migrator.ModelDiffer.Diff(snapshot.Model, dbContext.Model).Any();
                                    }

                                    if ((!databaseExists && pendingMigrations.Any()) || pendingMigrations.Any() || pendingModelChanges)
                                    {
                                        var page = new DatabaseErrorPage();
                                        page.Model = new DatabaseErrorPageModel(dbContextType, ex, databaseExists, pendingModelChanges, pendingMigrations, _options);
                                        await page.ExecuteAsync(context).WithCurrentCulture();

                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.WriteError(Strings.DatabaseErrorPageMiddleware_Exception, e);
                }

                throw;
            }
        }