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


C# IHttpContext类代码示例

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


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


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