当前位置: 首页>>代码示例>>C#>>正文


C# HttpContext.SetFeature方法代码示例

本文整理汇总了C#中Microsoft.AspNet.Http.HttpContext.SetFeature方法的典型用法代码示例。如果您正苦于以下问题:C# HttpContext.SetFeature方法的具体用法?C# HttpContext.SetFeature怎么用?C# HttpContext.SetFeature使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.AspNet.Http.HttpContext的用法示例。


在下文中一共展示了HttpContext.SetFeature方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Invoke

        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);
        }
开发者ID:knnithyanand,项目名称:Diagnostics,代码行数:27,代码来源:StatusCodePagesMiddleware.cs

示例2: Invoke

        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);
        }
开发者ID:RehanSaeed,项目名称:StaticFiles,代码行数:10,代码来源:SendFileMiddleware.cs

示例3: Invoke

        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);
                    }
                }
            }
        }
开发者ID:vagelious,项目名称:ergotaxionion,代码行数:42,代码来源:SessionMiddleware.cs

示例4: Invoke

        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);
        }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:12,代码来源:SendFileMiddleware.cs

示例5: Invoke

        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
            }
        }
开发者ID:RehanSaeed,项目名称:Diagnostics,代码行数:50,代码来源:ErrorHandlerMiddleware.cs

示例6: Invoke

        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);
        }
开发者ID:hitesh97,项目名称:WebSockets,代码行数:14,代码来源:WebSocketMiddleware.cs

示例7: GetExistingAsync

        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);
        }
开发者ID:geffzhang,项目名称:Bolt,代码行数:16,代码来源:DistributedSessionFactory.cs

示例8: CreateAsync

        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));
        }
开发者ID:geffzhang,项目名称:Bolt,代码行数:17,代码来源:DistributedSessionFactory.cs

示例9: RequestIdentifier

        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;
            }
        }
开发者ID:knnithyanand,项目名称:Diagnostics,代码行数:21,代码来源:RequestIdentifier.cs

示例10: Invoke

 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);
     }
 }
开发者ID:jchannon,项目名称:CustomStatusCodes,代码行数:23,代码来源:CustomStatusCodesMiddleware.cs

示例11: Invoke

        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);
        }
开发者ID:morarsebastian,项目名称:i18nStarterWeb,代码行数:36,代码来源:RequestLocalizationMiddleware.cs

示例12: GetRequestIdentifier

        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;
        }
开发者ID:Kagamine,项目名称:Hosting,代码行数:14,代码来源:HostingEngine.cs


注:本文中的Microsoft.AspNet.Http.HttpContext.SetFeature方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。