• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# IHttpContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: Respond

		public override void Respond(IHttpContext context)
		{
			var match = urlMatcher.Match(context.GetRequestUrl());
			var index = match.Groups[1].Value;

			var indexQuery = context.GetIndexQueryFromHttpContext(Database.Configuration.MaxPageSize);
			var facetStart = context.GetFacetStartFromHttpContext();
			var facetPageSize = context.GetFacetPageSizeFromHttpContext();

		    List<Facet> facets;

		    Etag etag;

            if (TryGetFacets(context, index, out etag, out facets) == false) 
				return;

			if (context.MatchEtag(etag))
			{
				context.SetStatusToNotModified();
				return;
			}

            context.WriteETag(etag);

            context.WriteJson(Database.ExecuteGetTermsQuery(index, indexQuery, facets, facetStart, facetPageSize));
		}
开发者ID:samueldjack,项目名称:ravendb,代码行数:26,代码来源:Facets.cs


示例2: Respond

		public override void Respond(IHttpContext context)
		{
			var src = context.Request.QueryString["from"];
			var dbid = context.Request.QueryString["dbid"];
			if (dbid == Database.TransactionalStorage.Id.ToString())
				throw new InvalidOperationException("Both source and target databases have database id = " + dbid + "\r\nDatabase cannot replicate to itself.");

			if (string.IsNullOrEmpty(src))
			{
				context.SetStatusToBadRequest();
				return;
			}
			while (src.EndsWith("/"))
				src = src.Substring(0, src.Length - 1);// remove last /, because that has special meaning for Raven
			if (string.IsNullOrEmpty(src))
			{
				context.SetStatusToBadRequest();
				return;
			}

			switch (context.Request.HttpMethod)
			{
				case "GET":
					OnGet(context, src);
					break;
				case "PUT":
					OnPut(context, src);
					break;	

			}
		}
开发者ID:robashton,项目名称:ravendb,代码行数:31,代码来源:ReplicationLastEtagResponder.cs


示例3: Respond

		public override void Respond(IHttpContext context)
		{
			BoundedMemoryTarget boundedMemoryTarget = null;
			if (LogManager.Configuration != null && LogManager.Configuration.AllTargets != null)
			{
				boundedMemoryTarget = LogManager.Configuration.AllTargets.OfType<BoundedMemoryTarget>().FirstOrDefault();
			}
			if(boundedMemoryTarget == null)
			{
				context.SetStatusToNotFound();
				context.WriteJson(new
				{
					Error = "HttpEndpoint was not registered in the log configuration, logs endpoint disable"
				});
				return;
			}
			IEnumerable<LogEventInfo> log = boundedMemoryTarget.GeneralLog;

			switch (context.Request.QueryString["type"])
			{
				case "error":
				case "warn":
					log = boundedMemoryTarget.WarnLog;
					break;
			}

			context.WriteJson(log.Select(x => new
			{
				x.TimeStamp,
				Message = x.FormattedMessage,
				x.LoggerName,
				Level = x.Level.Name,
				Exception = x.Exception == null ? null : x.Exception.ToString()
			}));
		}
开发者ID:neiz,项目名称:ravendb,代码行数:35,代码来源:Logs.cs


示例4: Send

 public override void Send(IHttpContext context)
 {
     context.StatusCode = httpStatusCode;
     Properties["message"] = message;
     Properties["errorId"] = errorId;
     base.Send(context);
 }
开发者ID:Ryks,项目名称:detergent,代码行数:7,代码来源:MvcErrorHttpResponse.cs


示例5: GetApprovedDatabases

		public override List<string> GetApprovedDatabases(IHttpContext context)
		{
			var user = context.User as OAuthPrincipal;
			if(user == null)
				return new List<string>();
			return user.GetApprovedDatabases();
		}
开发者ID:samueldjack,项目名称:ravendb,代码行数:7,代码来源:OAuthRequestAuthorizer.cs


示例6: HandleRequest

        public bool HandleRequest(IHttpContext context)
        {
            EnsureLogger(context.ServerInfo.LoggerFactory);

            var action = context.ServerInfo.ActionFactory.Create(actionType);
            var routeContext = new RouteContext(context, GetRouteData(context.Request.Url.AbsolutePath));

            IActionResult actionResult = null;
            switch (context.Request.HttpMethod.ToUpper())
            {
                case "GET":
                    logger.Debug("Dispatching GET request to {0}", action);
                    actionResult = action.Get(routeContext);
                    break;
                case "POST":
                    logger.Debug("Dispatching POST request to {0}", action);
                    actionResult = action.Post(routeContext);
                    break;
            }

            if (actionResult == null)
            {
                logger.Info("Action {0} did not handle the request", action);
                return false;
            }

            logger.Info("Request handled by action {0}, executing result...", action);
            actionResult.Execute(context);
            return true;
        }
开发者ID:Leafney,项目名称:SimpleHttpServer,代码行数:30,代码来源:Route.cs


示例7: Respond

		public override void Respond(IHttpContext context)
		{
			var match = urlMatcher.Match(context.GetRequestUrl());
			var docId = match.Groups[1].Value;
			switch (context.Request.HttpMethod)
			{
				case "GET":
					Get(context, docId);
					break;
				case "DELETE":
					Database.Delete(docId, context.GetEtag(), GetRequestTransaction(context));
					context.SetStatusToDeleted();
					break;
				case "PUT":
					Put(context, docId);
					break;
				case "PATCH":
					var patchRequestJson = context.ReadJsonArray();
					var patchRequests = patchRequestJson.Cast<RavenJObject>().Select(PatchRequest.FromJson).ToArray();
					var patchResult = Database.ApplyPatch(docId, context.GetEtag(), patchRequests, GetRequestTransaction(context));
					switch (patchResult)
					{
						case PatchResult.DocumentDoesNotExists:
							context.SetStatusToNotFound();
							break;
						case PatchResult.Patched:
							context.Response.AddHeader("Location", Database.Configuration.GetFullUrl("/docs/" + docId));
							context.WriteJson(new {Patched = true});
							break;
						default:
							throw new ArgumentOutOfRangeException("Value " + patchResult + " is not understood");
					}
					break;
			}
		}
开发者ID:wbinford,项目名称:ravendb,代码行数:35,代码来源:Document.cs


示例8: Respond

		public override void Respond(IHttpContext context)
		{
			var match = urlMatcher.Match(context.GetRequestUrl());
			var filename = match.Groups[1].Value;
			var etag = context.GetEtag();
			switch (context.Request.HttpMethod)
			{
				case "GET":
					var attachmentAndHeaders = Database.GetStatic(filename);
					if (attachmentAndHeaders == null)
					{
						context.SetStatusToNotFound();
						return;
					}
					if (context.MatchEtag(attachmentAndHeaders.Etag))
					{
						context.SetStatusToNotModified();
						return;
					}
					context.WriteData(attachmentAndHeaders.Data, attachmentAndHeaders.Metadata,
					                  attachmentAndHeaders.Etag);
					break;
				case "PUT":
					Database.PutStatic(filename, context.GetEtag(), context.Request.InputStream.ReadData(),
					                   context.Request.Headers.FilterHeaders(isServerDocument:false));
					context.SetStatusToCreated("/static/" + filename);
					break;
				case "DELETE":
					Database.DeleteStatic(filename, etag);
					context.SetStatusToDeleted();
					break;
			}
		}
开发者ID:nhsevidence,项目名称:ravendb,代码行数:33,代码来源:Static.cs


示例9: RespondToAdmin

		public override void RespondToAdmin(IHttpContext context)
		{
			var docEtagStr = context.Request.QueryString["docEtag"];
			Guid docEtag;
			var attachmentEtagStr = context.Request.QueryString["attachmentEtag"];
			Guid attachmentEtag;
			if (Guid.TryParse(docEtagStr, out docEtag) == false & // intentionally so, we want to eval both sides
				Guid.TryParse(attachmentEtagStr, out attachmentEtag) == false)
			{
				context.SetStatusToBadRequest();
				context.WriteJson(new
				{
					Error = "The query string variable 'docEtag' or 'attachmentEtag' must be set to a valid guid"
				});
				return;
			}

			Database.TransactionalStorage.Batch(accessor =>
			{
				if(docEtag != Guid.Empty)
				{
					accessor.Lists.RemoveAllBefore(Constants.RavenReplicationDocsTombstones, docEtag);
				}
				if(attachmentEtag != Guid.Empty)
				{
					accessor.Lists.RemoveAllBefore(Constants.RavenReplicationAttachmentsTombstones, attachmentEtag);
				}
			});
		}
开发者ID:nberardi,项目名称:ravendb,代码行数:29,代码来源:AdminPurgeTombstones.cs


示例10: Respond

		public override void Respond(IHttpContext context)
		{
			var match = urlMatcher.Match(context.GetRequestUrl());
			var docId = Uri.UnescapeDataString(match.Groups[1].Value);
			switch (context.Request.HttpMethod)
			{
				case "HEAD":
					Head(context, docId);
					break;
				case "GET":
					Get(context, docId);
					break;
				case "DELETE":
					Database.Delete(docId, context.GetEtag(), GetRequestTransaction(context));
					context.SetStatusToDeleted();
					break;
				case "PUT":
					Put(context, docId);
					break;
				case "PATCH":
					var patchRequestJson = context.ReadJsonArray();
					var patchRequests = patchRequestJson.Cast<RavenJObject>().Select(PatchRequest.FromJson).ToArray();
					var patchResult = Database.ApplyPatch(docId, context.GetEtag(), patchRequests, GetRequestTransaction(context));
					ProcessPatchResult(context, docId, patchResult.PatchResult, null);
					break;
				case "EVAL":
					var advPatchRequestJson = context.ReadJsonObject<RavenJObject>();
					var advPatch = ScriptedPatchRequest.FromJson(advPatchRequestJson);
					var advPatchResult = Database.ApplyPatch(docId, context.GetEtag(), advPatch, GetRequestTransaction(context), true);
					ProcessPatchResult(context, docId, advPatchResult.Item1.PatchResult, advPatchResult.Item2);
					break;
			}
		}
开发者ID:shiranGinige,项目名称:ravendb,代码行数:33,代码来源:Document.cs


示例11: Respond

		public override void Respond(IHttpContext context)
		{
			JArray itemsToLoad;
			if(context.Request.HttpMethod == "POST")
				itemsToLoad = context.ReadJsonArray();
			else
				itemsToLoad = new JArray(context.Request.QueryString.GetValues("id"));
			var result = new MultiLoadResult();
			var loadedIds = new HashSet<string>();
			var includes = context.Request.QueryString.GetValues("include") ?? new string[0];
			var transactionInformation = GetRequestTransaction(context);
			Database.TransactionalStorage.Batch(actions =>
			{
				var addIncludesCommand = new AddIncludesCommand(Database, transactionInformation, result.Includes.Add, includes, loadedIds);
				foreach (JToken item in itemsToLoad)
				{
					var value = item.Value<string>();
					if(loadedIds.Add(value)==false)
						continue;
					var documentByKey = actions.Documents.DocumentByKey(value,
                        transactionInformation);
					if (documentByKey == null)
						continue;
					result.Results.Add(documentByKey.ToJson());

					addIncludesCommand.Execute(documentByKey.DataAsJson);
				}
            });
			context.WriteJson(result);
		}
开发者ID:ajaishankar,项目名称:ravendb,代码行数:30,代码来源:Queries.cs


示例12: AdaptHttpContext

		private Action AdaptHttpContext(IHttpContext httpContext, ServerLog serverLog)
		{
			if (pathsToFilter.Contains(httpContext.Request.Url.AbsolutePath))
				return null;
			if (ignoreHilo && httpContext.Request.Url.AbsolutePath.StartsWith("/docs/Raven/Hilo/"))
				return null;
			if (httpContext.Request.Headers["Raven-Timer-Request"] != null)
				return null;

			var requestStream = new MemoryStream();
			httpContext.SetRequestFilter(stream =>
			{
				stream.CopyTo(requestStream);
				return new MemoryStream(requestStream.ToArray());
			});
			var responseStream = new MemoryStream();
			httpContext.SetResponseFilter(stream => new MultiStreamWriter(responseStream, stream));

			var trackedRequest = new TrackedRequest
			{
				Method = httpContext.Request.HttpMethod,
				Url = httpContext.Request.RawUrl,
				RequestHeaders = new NameValueCollection(httpContext.Request.Headers),
				RequestContent = requestStream,
				ResponseContent = responseStream,
				ResponseHeaders = httpContext.Response.GetHeaders(),
			};

			return () =>
			{
				trackedRequest.Status = httpContext.Response.StatusCode;
				serverLog.AddRequest(trackedRequest);
			};
		}
开发者ID:nberardi,项目名称:ravendb,代码行数:34,代码来源:Shell.cs


示例13: SessionStateContext

 public SessionStateContext(IHttpContext httpContext)
 {
     _httpContext = httpContext;
     SessionId = _httpContext.RequestCookies[AspNetSessionCookieName];
     MetabasePath = (string)_httpContext.ServerVariables[MetadataPathServerVariable];
     VirtualDirectoryPath = (string)_httpContext.ServerVariables[VirtualDirectoryPathServerVariable];
 }
开发者ID:mikeobrien,项目名称:ClassicAspRemoteSession,代码行数:7,代码来源:SessionStateContext.cs


示例14: Authorize

		public bool Authorize(IHttpContext context)
		{
			var requestUrl = context.GetRequestUrl();
			if (NeverSecret.Urls.Contains(requestUrl))
				return true;

			//CORS pre-flight (ignore creds if using cors).
			if (!String.IsNullOrEmpty(Settings.AccessControlAllowOrigin) && context.Request.HttpMethod == "OPTIONS")
			{ return true; }

			var oneTimeToken = context.Request.Headers["Single-Use-Auth-Token"];
			if (string.IsNullOrEmpty(oneTimeToken) == false)
			{
				return AuthorizeUsingleUseAuthToken(context, oneTimeToken);
			}

			var authHeader = context.Request.Headers["Authorization"];
			var hasApiKey = "True".Equals(context.Request.Headers["Has-Api-Key"], StringComparison.CurrentCultureIgnoreCase);
			var hasOAuthTokenInCookie = context.Request.HasCookie("OAuth-Token");
			if (hasApiKey || hasOAuthTokenInCookie ||
				string.IsNullOrEmpty(authHeader) == false && authHeader.StartsWith("Bearer "))
			{
				return oAuthRequestAuthorizer.Authorize(context, hasApiKey, IgnoreDb.Urls.Contains(requestUrl));
			}
			return windowsRequestAuthorizer.Authorize(context, IgnoreDb.Urls.Contains(requestUrl));
		}
开发者ID:925coder,项目名称:ravendb,代码行数:26,代码来源:MixedModeRequestAuthorizer.cs


示例15: Respond

		public override void Respond(IHttpContext context)
		{
			if (string.IsNullOrEmpty(context.Request.QueryString["no-op"]) == false)
			{
				// this is a no-op request which is there just to force the client HTTP layer to handle the authentication
				// only used for legacy clients
				return; 
			}
			if("generate-single-use-auth-token".Equals(context.Request.QueryString["op"],StringComparison.InvariantCultureIgnoreCase))
			{
				// using windows auth with anonymous access = none sometimes generate a 401 even though we made two requests
				// instead of relying on windows auth, which require request buffering, we generate a one time token and return it.
				// we KNOW that the user have access to this db for writing, since they got here, so there is no issue in generating 
				// a single use token for them.
				var token = server.RequestAuthorizer.GenerateSingleUseAuthToken(Database, context.User);
				context.WriteJson(new
				{
					Token = token
				});
				return;
			}

			if (HttpContext.Current != null)
			{
				HttpContext.Current.Server.ScriptTimeout = 60*60*6; // six hours should do it, I think.
			}
			var options = new BulkInsertOptions
			{
				CheckForUpdates = context.GetCheckForUpdates(),
				CheckReferencesInIndexes = context.GetCheckReferencesInIndexes()
			};

			var operationId = ExtractOperationId(context);
			var sp = Stopwatch.StartNew();

			var status = new BulkInsertStatus();

			int documents = 0;
			var mre = new ManualResetEventSlim(false);

			var currentDatbase = Database;
			var task = Task.Factory.StartNew(() =>
			{
				currentDatbase.BulkInsert(options, YieldBatches(context, mre, batchSize => documents += batchSize), operationId);
			    status.Documents = documents;
			    status.Completed = true;
			});

			long id;
			Database.AddTask(task, status, out id);

			mre.Wait(Database.WorkContext.CancellationToken);

			context.Log(log => log.Debug("\tBulk inserted received {0:#,#;;0} documents in {1}, task #: {2}", documents, sp.Elapsed, id));

			context.WriteJson(new
			{
				OperationId = id
			});
		}
开发者ID:robashton,项目名称:ravendb,代码行数:60,代码来源:BulkInsert.cs


示例16: HandleRequest

        public ModuleResult HandleRequest(IHttpContext context)
        {
            if (OnListenerNotify != null)
                OnListenerNotify(null, new ListenerNotifyEventArgs() { Context = context });

            return ModuleResult.Stop;
        }
开发者ID:mars-huang,项目名称:Griffin.WebServer,代码行数:7,代码来源:MyModule.cs


示例17: GetApprovedDatabases

		public override List<string> GetApprovedDatabases(IPrincipal user, IHttpContext context = null)
		{
			var oAuthUser = user as OAuthPrincipal;
			if (oAuthUser == null)
				return new List<string>();
			return oAuthUser.GetApprovedDatabases();
		}
开发者ID:phinett,项目名称:ravendb,代码行数:7,代码来源:OAuthRequestAuthorizer.cs


示例18: CheckFileSystem

        private ActionResult CheckFileSystem(IHttpContext context)
        {
            string path = _webUIPath + (context.Request.Url.AbsolutePath == "/" ? "/index.html" : context.Request.Url.AbsolutePath);

            if (_fileSystem.FileExists(path))
            {
                string contentType = "text/html";

                switch (Path.GetExtension(path))
                {
                    case ".css":
                        contentType = "text/css";
                        break;

                    case ".js":
                        contentType = "text/javascript";
                        break;

                    case ".png":
                        contentType = "image/png";
                        break;

                    case ".gif":
                        contentType = "image/gif";
                        break;
                }

                return new ContentResult { Content = _fileSystem.ReadAllBytes(path), ContentType = contentType };
            }

            return null;
        }
开发者ID:randacc,项目名称:hdkn,代码行数:32,代码来源:DefaultHttpServer.cs


示例19: ControllerContext

 /// <summary>
 /// Initializes a new instance of the <see cref="ControllerContext"/> class.
 /// </summary>
 /// <param name="context">Request context.</param>
 public ControllerContext(IHttpContext context)
 {
     ViewData = new ViewData();
     HttpContext = context;
     Uri = context.Request.Uri;
     UriRewrite = context.Request.Uri;
 }
开发者ID:marinehero,项目名称:microserver,代码行数:11,代码来源:ControllerContext.cs


示例20: Respond

        /// <summary>
        /// Responds the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public override void Respond(IHttpContext context)
        {
            var match = urlMatcher.Match(context.GetRequestUrl());
            var index = match.Groups[1].Value;
            
            var term = context.Request.QueryString["term"];
            var field = context.Request.QueryString["field"];

            StringDistanceTypes distanceTypes;
            int numOfSuggestions;
            float accuracy;

            if (Enum.TryParse(context.Request.QueryString["distance"], true, out distanceTypes) == false)
                distanceTypes =StringDistanceTypes.Default;

            if (int.TryParse(context.Request.QueryString["max"], out numOfSuggestions) == false)
                numOfSuggestions = 10;

            if(float.TryParse(context.Request.QueryString["accuracy"], out accuracy) == false)
                accuracy = 0.5f;

            var query = new SuggestionQuery
                            {
                                Distance = distanceTypes,
                                Field = field,
                                MaxSuggestions = numOfSuggestions,
                                Term = term,
                                Accuracy = accuracy
                            };

            var suggestionQueryResult = Database.ExecuteSuggestionQuery(index, query);
            context.WriteJson(suggestionQueryResult);
        }
开发者ID:nzdunic,项目名称:ravendb,代码行数:37,代码来源:SuggestionResponder.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IHttpContextAccessor类代码示例发布时间:2022-05-24
下一篇:
C# IHttpClientContext类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap