public async Task Invoke(HttpContext context)
        {
            var statusCodeFeature = new StatusCodePagesFeature();
            context.SetFeature<IStatusCodePagesFeature>(statusCodeFeature);

            await _next(context);

            if (!statusCodeFeature.Enabled)
            {
                // Check if the feature is still available because other middleware (such as a web API written in MVC) could
                // have disabled the feature to prevent HTML status code responses from showing up to an API client.
                return;
            }

            // Do nothing if a response body has already been provided.
            if (context.Response.HasStarted
                || context.Response.StatusCode < 400
                || context.Response.StatusCode >= 600
                || context.Response.ContentLength.HasValue
                || !string.IsNullOrEmpty(context.Response.ContentType))
            {
                return;
            }

            var statusCodeContext = new StatusCodeContext(context, _options, _next);
            await _options.HandleAsync(statusCodeContext);
        }
        public Task Invoke(HttpContext context)
        {
            // Check if there is a SendFile feature already present
            if (context.GetFeature<IHttpSendFileFeature>() == null)
            {
                context.SetFeature<IHttpSendFileFeature>(new SendFileWrapper(context.Response.Body, _logger));
            }

            return _next(context);
        }
        public async Task Invoke(HttpContext context)
        {
            var isNewSessionKey = false;
            Func<bool> tryEstablishSession = ReturnTrue;
            var sessionKey = context.Request.Cookies.Get(_options.CookieName);
            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                CryptoRandom.GetBytes(guidBytes);
                sessionKey = new Guid(guidBytes).ToString();
                var establisher = new SessionEstablisher(context, sessionKey, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey = true;
            }

            var feature = new SessionFeature();
            feature.Factory = new SessionFactory(sessionKey, _options.Store, _options.IdleTimeout, tryEstablishSession, isNewSessionKey);
            feature.Session = feature.Factory.Create();
            context.SetFeature<ISessionFeature>(feature);

            try
            {
                await _next(context);
            }
            finally
            {
                context.SetFeature<ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        feature.Session.Commit();
                    }
                    catch (Exception ex)
                    {
                        _logger.WriteError("Error closing the session.", ex);
                    }
                }
            }
        }
        public async Task Invoke(HttpContext context)
        {
            var environment = (IApplicationEnvironment)context.RequestServices.GetService(typeof(IApplicationEnvironment));

            if (context.GetFeature<IHttpSendFileFeature>() == null)
            {
                var sendFile = new SendFileFallBack(context.Response.Body, environment.ApplicationBasePath);
                context.SetFeature<IHttpSendFileFeature>(sendFile);
            }

            await _next(context);
        }
        public async Task Invoke(HttpContext context)
        {
            var responseStarted = false;
            try
            {
                context.Response.OnSendingHeaders(state => responseStarted = true, null);
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError("An unhandled exception has occurred: " + ex.Message, ex);
                // We can't do anything if the response has already started, just abort.
                if (responseStarted)
                {
                    _logger.LogWarning("The response has already started, the error handler will not be executed.");
                    throw;
                }

                PathString originalPath = context.Request.Path;
                if (_options.ErrorHandlingPath.HasValue)
                {
                    context.Request.Path = _options.ErrorHandlingPath;
                }
                try
                {
                    var errorHandlerFeature = new ErrorHandlerFeature()
                    {
                        Error = ex,
                    };
                    context.SetFeature<IErrorHandlerFeature>(errorHandlerFeature);
                    context.Response.StatusCode = 500;
                    context.Response.Headers.Clear();
                    // TODO: Try clearing any buffered data. The buffering feature/middleware has not been designed yet.
                    await _options.ErrorHandler(context);
                    // TODO: Optional re-throw? We'll re-throw the original exception by default if the error handler throws.
                    return;
                }
                catch (Exception ex2)
                {
                    // Suppress secondary exceptions, re-throw the original.
                    _logger.LogError("An exception was thrown attempting to execute the error handler.", ex2);
                }
                finally
                {
                    context.Request.Path = originalPath;
                }

                throw; // Re-throw the original if we couldn't handle it
            }
        }
        public Task Invoke(HttpContext context)
        {
            // Detect if an opaque upgrade is available. If so, add a websocket upgrade.
            var upgradeFeature = context.GetFeature<IHttpUpgradeFeature>();
            if (upgradeFeature != null)
            {
                if (_options.ReplaceFeature || context.GetFeature<IHttpWebSocketFeature>() == null)
                {
                    context.SetFeature<IHttpWebSocketFeature>(new UpgradeHandshake(context, upgradeFeature, _options));
                }
            }

            return _next(context);
        }
        public async Task<IContractSession> GetExistingAsync(HttpContext context, Func<Task<object>> instanceFactory)
        {
            var sessionId = _sessionHandler.GetIdentifier(context);

            if (string.IsNullOrEmpty(sessionId))
            {
                throw new SessionHeaderNotFoundException();
            }

            // establish session
            ISession session = _sessionStore.Create(sessionId, SessionTimeout, () => true, false);
            context.SetFeature<ISessionFeature>(new SessionFeature());
            context.Session = session;

            return new DistributedContractSession(sessionId, await instanceFactory(), session);
        }
        public Task<IContractSession> CreateAsync(HttpContext context, object instance)
        {
            var sessionId = _sessionHandler.GetIdentifier(context);
            if (sessionId != null)
            {
                _sessionHandler.Destroy(context);
            }

            sessionId = _sessionHandler.Initialize(context);

            // establish session
            ISession session = _sessionStore.Create(sessionId, SessionTimeout, () => true, true);
            context.SetFeature<ISessionFeature>(new SessionFeature());
            context.Session = session;

            return Task.FromResult((IContractSession)new DistributedContractSession(sessionId, instance, session));
        }
        private RequestIdentifier(HttpContext context)
        {
            _context = context;
            _feature = context.GetFeature<IHttpRequestIdentifierFeature>();

            if (_feature == null)
            {
                _feature = new HttpRequestIdentifierFeature()
                {
                    TraceIdentifier = Guid.NewGuid().ToString()
                };
                context.SetFeature(_feature);
                _addedFeature = true;
            }
            else if (string.IsNullOrEmpty(_feature.TraceIdentifier))
            {
                _originalIdentifierValue = _feature.TraceIdentifier;
                _feature.TraceIdentifier = Guid.NewGuid().ToString();
                _updatedIdentifier = true;
            }
        }
 public async Task Invoke(HttpContext context)
 {
     context.SetFeature<BackupStreamFeature>(new BackupStreamFeature() { Body = context.Response.Body });
     context.Response.Body = new StreamWrapper(context.Response.Body, InspectStatusCode, context);
     await _next.Invoke(context);
     
     StatusCodeAction action;
     int statusCode = context.Response.StatusCode;
     bool? replace = context.GetFeature<BackupStreamFeature>().Replace;
     if (!replace.HasValue)
     {
         // Never evaluated, no response sent yet.
         if (options.StatusCodeActions.TryGetValue(statusCode, out action)
             && action != StatusCodeAction.Ignore)
         {
             await options.ResponseGenerator(context);
         }
     }
     else if (replace.Value == true)
     {
         await options.ResponseGenerator(context);
     }
 }
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.QueryString.HasValue)
            {
                var queryCulture = context.Request.Query["culture"];
                if (!string.IsNullOrEmpty(queryCulture))
                {
                    var culture = new CultureInfo(queryCulture);

                    context.SetFeature<IRequestCultureFeature>(new RequestCultureFeature(culture));

                    var originalCulture = CultureInfo.CurrentCulture;
                    var originalUICulture = CultureInfo.CurrentUICulture;

                    SetCurrentCulture(culture, culture);

                    await _next(context);

                    // NOTE: If we're on a different thread now the culture is not here but is still on the old thread
                    //       which could be used on another request. This will be fixed by the XRE.

                    SetCurrentCulture(originalCulture, originalUICulture);

                    return;
                }
            }
            else
            {
                // Forcibly set thread to en-US as sometimes previous threads have wrong culture across async calls, 
                // see note above.
                var defaultCulture = new CultureInfo("en-US");
                SetCurrentCulture(defaultCulture, defaultCulture);
            }

            await _next(context);
        }
Beispiel #12
0
        private string GetRequestIdentifier(HttpContext httpContext)
        {
            var requestIdentifierFeature = httpContext.GetFeature<IHttpRequestIdentifierFeature>();
            if (requestIdentifierFeature == null)
            {
                requestIdentifierFeature = new HttpRequestIdentifierFeature()
                {
                    TraceIdentifier = Guid.NewGuid().ToString()
                };
                httpContext.SetFeature(requestIdentifierFeature);
            }

            return requestIdentifierFeature.TraceIdentifier;
        }