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


C# Http.HttpContext类代码示例

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


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

示例1: Invoke

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError("An unhandled exception has occurred while executing the request", ex);
                if (context.Response.HasStarted)
                {
                    _logger.LogWarning("The response has already started, the error page middleware will not be executed.");
                    throw;
                }

                try
                {
                    context.Response.Clear();
                    context.Response.StatusCode = 500;

                    await DisplayException(context, ex);
                    return;
                }
                catch (Exception ex2)
                {
                    // If there's a Exception while generating the error page, re-throw the original exception.
                    _logger.LogError("An exception was thrown attempting to display the error page.", ex2);
                }
                throw;
            }
        }
开发者ID:ryanbrandenburg,项目名称:Diagnostics,代码行数:31,代码来源:DeveloperExceptionPageMiddleware.cs

示例2: Invoke

        public async Task Invoke(HttpContext context)
        {
            using (var memoryStream = new MemoryStream())
            {
                var bodyStream = context.Response.Body;
                context.Response.Body = memoryStream;

                await _next(context);

                var isHtml = context.Response.ContentType?.ToLower().Contains("text/html");
                if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault())
                {
                    {
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        using (var streamReader = new StreamReader(memoryStream))
                        {
                            string body = await streamReader.ReadToEndAsync();
                            body = MinifyHtml(body);
                            using (var minBodyStream = new MemoryStream())
                            using (var streamWriter = new StreamWriter(minBodyStream))
                            {
                                streamWriter.Write(body);
                                streamWriter.Flush();
                                minBodyStream.Seek(0, SeekOrigin.Begin);
                                await minBodyStream.CopyToAsync(bodyStream);
                            }
                        }
                    }
                }
            }
        }
开发者ID:okusnadi,项目名称:HtmlMinifier,代码行数:31,代码来源:HtmlMinifierMiddleWare.cs

示例3: Match

        //private string requiredSiteFolder;

        //public SiteFolderRouteConstraint(string folderParam)
        //{
        //    requiredSiteFolder = folderParam;
        //}

        public bool Match(
            HttpContext httpContext,
            IRouter route,
            string parameterName,
            IDictionary<string,object> values,
            RouteDirection routeDirection)
        {
            string requestFolder = RequestSiteResolver.GetFirstFolderSegment(httpContext.Request.Path);
            //return string.Equals(requiredSiteFolder, requestFolder, StringComparison.CurrentCultureIgnoreCase);
            ISiteResolver siteResolver = httpContext.ApplicationServices.GetService<ISiteResolver>();
            if(siteResolver != null)
            {
                try
                {
                    // exceptions expected here until db install scripts have run or if db connection error
                    ISiteSettings site = siteResolver.Resolve();
                    if ((site != null) && (site.SiteFolderName == requestFolder)) { return true; }
                }
                catch
                {
                    // do we need to log this?
                }

            }

            return false;
        }
开发者ID:ludev,项目名称:cloudscribe,代码行数:34,代码来源:SiteFolderRouteConstraint.cs

示例4: Invoke

        /// <summary>
        /// Executes the middleware.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
        /// <returns>A task that represents the execution of this middleware.</returns>
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            PathString path = context.Request.Path;
            PathString remainingPath;
            if (path.StartsWithSegments(_options.PathMatch, out remainingPath))
            {
                // Update the path
                PathString pathBase = context.Request.PathBase;
                context.Request.PathBase = pathBase + _options.PathMatch;
                context.Request.Path = remainingPath;

                try
                {
                    await _options.Branch(context);
                }
                finally
                {
                    context.Request.PathBase = pathBase;
                    context.Request.Path = path;
                }
            }
            else
            {
                await _next(context);
            }
        }
开发者ID:leloulight,项目名称:HttpAbstractions,代码行数:36,代码来源:MapMiddleware.cs

示例5: Invoke

 public async Task Invoke(HttpContext context)
 {
     if (context.Request.Headers.ContainsKey("Authorization"))
     {
         var token = Convert.FromBase64String(context.Request.Headers["Authorization"]);
         if (token.Length > 3 && token.Length < 91)
         {
             // handshake state 2 - CHALLENGE
             context.Response.StatusCode = StatusCodes.Status401Unauthorized;
             context.Response.Headers.Add("WWW-Authenticate", "NTLM TlRMTVNTUAACAAAAHgAeADgAAAAFwoqi4OsyKS+KwHxArb4Q4wAAAJgAmABWAAAACgAAKAAAAA9EAEUAUwBLAFQATwBQAC0ANwBRAEsANABLAEMASgACAB4ARABFAFMASwBUAE8AUAAtADcAUQBLADQASwBDAEoAAQAeAEQARQBTAEsAVABPAFAALQA3AFEASwA0AEsAQwBKAAQAHgBEAEUAUwBLAFQATwBQAC0ANwBRAEsANABLAEMASgADAB4ARABFAFMASwBUAE8AUAAtADcAUQBLADQASwBDAEoABwAIAAWsUmSNW9EBAAAAAA==");
             return;
         } 
         else if (token.Length > 90)
         {
             // handshake state 3 - AUTHENTICATED
         }
         else 
         {
             // handshake state 1 - NEGOTIATE
             context.Response.StatusCode = StatusCodes.Status401Unauthorized;
             context.Response.Headers.Add("WWW-Authenticate", "NTLM");
             return;
         }
     }
     else
     {
         // handshake state 1 - NEGOTIATE
         context.Response.StatusCode = StatusCodes.Status401Unauthorized;
         context.Response.Headers.Add("WWW-Authenticate", "NTLM");
         return;    
     }
     
     await _next(context);
 }
开发者ID:revlucio,项目名称:Revlucio.NtlmAuthentication,代码行数:34,代码来源:NtlmAuthenticationMiddleware.cs

示例6: Respond

        public async Task Respond(HttpContext context)
        {
            // Get path
            Match match = new Regex(_request_regex_pattern).Match(context.Request.Path);

            int length = match.Groups.Count;
            if (length < 2)
                length = 2;
            string[] matches = new string[length];
            matches[1] = "";
            for (int i = 0; i < match.Groups.Count; i++)
            {
                matches[i] = match.Groups[i].Value;
            }
            string file_path = String.Format(_file_directory, matches);
             
            // Check existance
            if (!File.Exists(file_path))
            {
                IHttpHandler error_handler = new ErrorHandler(404);
                await error_handler.Respond(context);
                return;
            }

            // Change content type if needed
            string ext = Path.GetExtension(file_path);
            if (_content_types.ContainsKey(ext))
            {
                context.Response.ContentType = _content_types[ext];
            }
            
            await context.Response.SendFile(file_path);
        }
开发者ID:Martin1994,项目名称:pp9k,代码行数:33,代码来源:StaticHandler.cs

示例7: GetAndCacheAllMatchingValues

        private string[] GetAndCacheAllMatchingValues(string routeKey, HttpContext httpContext)
        {
            var actionDescriptors = GetAndValidateActionDescriptorsCollection(httpContext);
            var version = actionDescriptors.Version;
            var valuesCollection = _cachedValuesCollection;

            if (valuesCollection == null ||
                version != valuesCollection.Version)
            {
                var routeValueCollection = actionDescriptors
                                            .Items
                                            .Select(ad => ad.RouteConstraints
                                                            .FirstOrDefault(
                                                                c => c.RouteKey == routeKey &&
                                                                c.KeyHandling == RouteKeyHandling.RequireKey))
                                            .Where(rc => rc != null)
                                            .Select(rc => rc.RouteValue)
                                            .Distinct()
                                            .ToArray();

                valuesCollection = new RouteValuesCollection(version, routeValueCollection);
                _cachedValuesCollection = valuesCollection;
            }

            return _cachedValuesCollection.Items;
        }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:26,代码来源:KnownRouteValueConstraint.cs

示例8: Invoke

        public async Task Invoke(HttpContext httpContext)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Begin Routing Request");
            }

            var shellSettings = httpContext.RequestServices.GetService<ShellSettings>();
            var routerTable = httpContext.ApplicationServices.GetService<IRunningShellRouterTable>();

            var router = routerTable.GetOrAdd(
                shellSettings.Name, 
                name => httpContext.RequestServices.GetService<IRouteBuilder>().Build()
            );

            var context = new RouteContext(httpContext);
            context.RouteData.Routers.Add(router);

            await router.RouteAsync(context);

            if (!context.IsHandled)
            {
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Request did not match any routes.");
                }

                await _next.Invoke(httpContext);
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("End Routing Request");
            }
        }
开发者ID:mzgnr,项目名称:Orchard2,代码行数:35,代码来源:OrchardRouterMiddleware.cs

示例9: Invoke

        public Task Invoke(HttpContext httpContext)
        {
            string cacheKey = "GreetingMiddleware-Invoke";
            string greeting;

            // try to get the cached item; null if not found
            // greeting = _memoryCache.Get(cacheKey) as string;

            // alternately, TryGet returns true if the cache entry was found
            if(!_memoryCache.TryGetValue(cacheKey, out greeting))
            {
                // fetch the value from the source
                greeting = _greetingService.Greet("world");

                // store in the cache
                _memoryCache.Set(cacheKey, greeting,
                    new MemoryCacheEntryOptions()
                    .SetAbsoluteExpiration(TimeSpan.FromMinutes(1)));
                _logger.LogInformation($"{cacheKey} updated from source.");
            }
            else
            {
                _logger.LogInformation($"{cacheKey} retrieved from cache.");
            }

            return httpContext.Response.WriteAsync(greeting);
        }
开发者ID:ChujianA,项目名称:aspnetcore-doc-cn,代码行数:27,代码来源:GreetingMiddleware.cs

示例10: ProcessRequestAsync

        public static async Task ProcessRequestAsync(HttpContext Context, string Action) {
            var form = Context.Request.Form;
            Context.Response.ContentType = "text/javascript";

            switch (Action) {
                case Forms.TakeThePledge.Action.Form:
                    var businessName = form[Forms.TakeThePledge.Keys.BusinessName];
                    var address = form[Forms.TakeThePledge.Keys.Address];
                    var manager = form[Forms.TakeThePledge.Keys.OwnerManagerName];
                    var phoneNumber = form[Forms.TakeThePledge.Keys.PhoneNumber];
                    var email = form[Forms.TakeThePledge.Keys.Email];
                    var website = form[Forms.TakeThePledge.Keys.Website];

                    string message = $"Business Name: {businessName}\r\nAddress: {address}\r\nOwner/Manager: {manager}\r\nPhone Number: {phoneNumber}\r\nEmail: {email}\r\nWebsite: {website}";

                    try {
                        var e = new Site.Email() { To = Application.TakeThePledge.Form.EmailTo, Subject = "New Business Took Bag Free Portsmouth Pledge", Body = message };

                        if (_queue == null) {
                            _queue = CloudStorageAccount.Parse($"DefaultEndpointsProtocol=https;AccountName={Application.Queue.Name};AccountKey={Application.Queue.Key}").CreateCloudQueueClient().GetQueueReference(Application.Queue.Name);
                        }
                        await _queue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(e)));
                        await Context.Response.WriteAsync(Response.Substitute(Forms.TakeThePledge.HtmlID.FormContainer, "<div class=\"tac blue\">Thanks! Your information has been received and you'll be contacted shortly.</div>"));
                    } catch {
                        await Context.Response.WriteAsync(Response.Substitute(Forms.TakeThePledge.HtmlID.FormContainer, $"<div class=\"tac blue\">Sorry, there was an error processing the form.</div>"));
                    }
                    break;
            }
        }
开发者ID:matthewhancock,项目名称:plasticbagfreeportsmouth,代码行数:29,代码来源:Post.cs

示例11: Invoke

        public async Task Invoke(HttpContext httpContext)
        {
            // We check Ordinal explicitly first because it's faster than OrdinalIgnoreCase
            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal) ||
                httpContext.Request.Path.StartsWithSegments(_path, StringComparison.OrdinalIgnoreCase))
            {
                var db = (ApplicationDbContext)httpContext.RequestServices.GetService(typeof(ApplicationDbContext));

                db.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

                var id = _random.Next(1, 10001);
                var row = await db.World.SingleAsync(w => w.Id == id);
                var result = JsonConvert.SerializeObject(row);

                httpContext.Response.StatusCode = 200;
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.ContentLength = result.Length;

                await httpContext.Response.WriteAsync(result);

                return;
            }

            await _next(httpContext);
        }
开发者ID:thehousecat,项目名称:benchmarks,代码行数:25,代码来源:SingleQueryEfMiddleware.cs

示例12: OAuthChallengeContext

 /// <summary>
 /// Initializes a new <see cref="OAuthRequestTokenContext"/>
 /// </summary>
 /// <param name="context">HTTP environment</param>
 /// <param name="challenge">The www-authenticate header value.</param>
 public OAuthChallengeContext(
     HttpContext context,
     string challenge)
     : base(context)
 {
     Challenge = challenge;
 }
开发者ID:SacmaIslerOfisi,项目名称:Security,代码行数:12,代码来源:OAuthChallengeContext.cs

示例13: Invoke

        public async Task Invoke(HttpContext httpContext, RequestTelemetry telemetry)
        {
            telemetry.Timestamp = DateTimeOffset.UtcNow;

            var sw = new Stopwatch();
            sw.Start();

            bool requestFailed = false;

            try
            {
                await this.next.Invoke(httpContext);
            }
            catch (Exception)
            {
                requestFailed = true;
                throw;
            }
            finally
            {
                sw.Stop();

                telemetry.Duration = sw.Elapsed;
                telemetry.ResponseCode = httpContext.Response.StatusCode.ToString();
                telemetry.Success = (!requestFailed) && (httpContext.Response.StatusCode < 400);
                telemetry.HttpMethod = httpContext.Request.Method;
                telemetry.Url = httpContext.Request.GetUri();
                telemetry.Context.GetInternalContext().SdkVersion = this.sdkVersion;
                    
                this.telemetryClient.TrackRequest(telemetry);
            }
        }
开发者ID:modulexcite,项目名称:ApplicationInsights-aspnet5,代码行数:32,代码来源:RequestTrackingMiddleware.cs

示例14: Invoke

        public async Task Invoke(HttpContext httpContext, UserManager<ApplicationUser> manager)
        {
            if (httpContext.Request.Path.StartsWithSegments(_options.Path))
            {
                var headers = httpContext.Request.Headers;
                if (!(headers.ContainsKey("ApiUser") && headers.ContainsKey("ApiToken")))
                {
                    await httpContext.Authentication.ChallengeAsync();
                    return;
                }

                var apiUser = headers.FirstOrDefault(h => h.Key == "ApiUser").Value;
                var token = headers.FirstOrDefault(h => h.Key == "ApiToken").Value;

                var user = await manager.FindByNameAsync(apiUser).ConfigureAwait(false);
                var authorized = await manager.VerifyUserTokenAsync(user, "Default", "api-request-injest", token).ConfigureAwait(false);

                if (!authorized)
                {
                    await httpContext.Authentication.ChallengeAsync();
                    return;
                }
            }

            await _next(httpContext);
        }
开发者ID:yobenzima,项目名称:allReady,代码行数:26,代码来源:TokenProtectedResource.cs

示例15: Invoke

        public async Task Invoke(HttpContext httpContext)
        {
            // We check Ordinal explicitly first because it's faster than OrdinalIgnoreCase
            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal) ||
                httpContext.Request.Path.StartsWithSegments(_path, StringComparison.OrdinalIgnoreCase))
            {
                httpContext.Response.ContentType = "text/html";

                await httpContext.Response.WriteAsync("<h1>Application Information</h1>");
                await httpContext.Response.WriteAsync("<ul>");

                await httpContext.Response.WriteAsync($"<li>Environment: {_hostingEnv.EnvironmentName}</li>");
                await httpContext.Response.WriteAsync($"<li>Framework: {_appEnv.RuntimeFramework.FullName}</li>");
                await httpContext.Response.WriteAsync($"<li>Configuration: {_configurationName}</li>");
                await httpContext.Response.WriteAsync($"<li>Server: {_hostingEnv.Configuration["server"]}</li>");
                await httpContext.Response.WriteAsync($"<li>Server URLs: {_hostingEnv.Configuration["server.urls"]}</li>");
                await httpContext.Response.WriteAsync($"<li>Supports Send File: {httpContext.Response.SupportsSendFile()}</li>");

                await httpContext.Response.WriteAsync($"<li>Server features:<ul>");
                
                foreach (var feature in httpContext.Features)
                {
                    await httpContext.Response.WriteAsync($"<li>{feature.Key.Name}</li>");
                }
                await httpContext.Response.WriteAsync($"</ul></li>");

                await httpContext.Response.WriteAsync("</ul>");
                return;
            }

            await _next(httpContext);
        }
开发者ID:AspNetSmurfLab,项目名称:benchmarks,代码行数:32,代码来源:DebugInfoPageMiddleware.cs


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