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


C# IHttpContext.Write方法代码示例

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


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

示例1: Respond

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

			var facetSetupDoc = context.GetFacetSetupDocFromHttpContext();
			var indexQuery = context.GetIndexQueryFromHttpContext(Database.Configuration.MaxPageSize);

			var jsonDocument = Database.Get(facetSetupDoc, null);
			if(jsonDocument == null)
			{
				context.SetStatusToNotFound();
				context.Write("Could not find facet document: " + facetSetupDoc);
				return;
			}

			var etag = GetFacetsEtag(jsonDocument, index);

			if(context.MatchEtag(etag))
			{
				context.SetStatusToNotModified();
				return;
			}
			context.WriteETag(etag);
			context.WriteJson(Database.ExecuteGetTermsQuery(index, indexQuery, facetSetupDoc));
		}
开发者ID:remcoros,项目名称:ravendb,代码行数:26,代码来源:Facets.cs

示例2: HandlePut

	    private void HandlePut(IHttpContext context, string transformer)
	    {
	        var data = context.ReadJsonObject<TransformerDefinition>();
	        if (data == null || string.IsNullOrEmpty(data.TransformResults))
	        {
	            context.SetStatusToBadRequest();
	            context.Write("Expected json document with 'TransformResults' property");
	            return;
	        }

	        try
	        {
	            var transformerName = Database.PutTransform(transformer, data);
	            context.SetStatusToCreated("/transformers");
	            context.WriteJson(new {Transformer = transformerName});
	        }
            catch (Exception ex)
            {
                context.SetStatusToBadRequest();
                context.WriteJson(new
                {
                    Message = ex.Message,
                    Error = ex.ToString()
                });
            }
	    }
开发者ID:nzaugg,项目名称:ravendb,代码行数:26,代码来源:Transformers.cs

示例3: TryGetFacets

		private bool TryGetFacets(IHttpContext context, string index, out Etag etag, out List<Facet> facets)
		{
			etag = null;
			facets = null;
			switch (context.Request.HttpMethod)
			{
				case "GET":
					var facetSetupDoc = context.GetFacetSetupDocFromHttpContext();
					if (string.IsNullOrEmpty(facetSetupDoc))
					{
						var facetsJson = context.Request.QueryString["facets"];
						if (string.IsNullOrEmpty(facetsJson) == false)
							return TryGetFacetsFromString(context, index, out etag, out facets, facetsJson);
					}

					JsonDocument jsonDocument = Database.Get(facetSetupDoc, null);
					if (jsonDocument == null)
					{
						context.SetStatusToNotFound();
						context.Write("Could not find facet document: " + facetSetupDoc);
						return false;
					}

					etag = GetFacetsEtag(jsonDocument, index);

					facets = jsonDocument.DataAsJson.JsonDeserialization<FacetSetup>().Facets;

					if (facets == null || !facets.Any())
					{
						context.SetStatusToNotFound();
						context.Write("No facets found in facets setup document:" + facetSetupDoc);
						return false;
					}
					break;
				case "POST":
					return TryGetFacetsFromString(context, index, out etag, out facets, context.ReadString());
				default:
					context.SetStatusToBadRequest();
					context.Write("No idea how to handle this request");
					break;
			}
			return true;
		}
开发者ID:samueldjack,项目名称:ravendb,代码行数:43,代码来源:Facets.cs

示例4: Put

		private void Put(IHttpContext context, string index)
		{
			var data = context.ReadJsonObject<IndexDefinition>();
			if (data == null || (data.Map == null && (data.Maps == null || data.Maps.Count == 0)))
			{
				context.SetStatusToBadRequest();
				context.Write("Expected json document with 'Map' or 'Maps' property");
				return;
			}
			context.SetStatusToCreated("/indexes/" + index);
			context.WriteJson(new { Index = Database.PutIndex(index, data) });
		}
开发者ID:MikeEast,项目名称:ravendb,代码行数:12,代码来源:Index.cs

示例5: Respond

		public override void Respond(IHttpContext context)
		{
			if (context.Request.Headers["Accept"] != TokenContentType)
			{
				context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
				context.WriteJson(new { error = "invalid_request", error_description = "Accept should be: " + TokenContentType });

				return;
			}

			if (context.Request.Headers["grant_type"] != TokenGrantType)
			{
				context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
				context.WriteJson(new { error = "unsupported_grant_type", error_description = "Only supported grant_type is: " + TokenGrantType });

				return;
			}

			var identity = GetUserAndPassword(context);

			if (identity == null)
			{
				context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
				context.Response.AddHeader("WWW-Authenticate", "Basic realm=\"Raven DB\"");
				context.WriteJson(new { error = "invalid_client", error_description = "No client authentication was provided" });

				return;
			}

			string[] authorizedDatabases;
			if (!AuthenticateClient.Authenticate(ResourceStore, identity.Item1, identity.Item2, out authorizedDatabases))
			{
				if ((ResourceStore == DefaultResourceStore ||
				     !AuthenticateClient.Authenticate(DefaultResourceStore, identity.Item1, identity.Item2, out authorizedDatabases)))
				{
					context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
					context.Response.AddHeader("WWW-Authenticate", "Basic realm=\"Raven DB\"");
					context.WriteJson(new { error = "unauthorized_client", error_description = "Invalid client credentials" });

					return;
				}
			}

			Interlocked.Increment(ref numberOfTokensIssued);

			var userId = identity.Item1;

			var token = AccessToken.Create(Settings.OAuthTokenCertificate, userId,
										   authorizedDatabases);

			context.Write(token.Serialize());
		}
开发者ID:quenth,项目名称:ravendb,代码行数:52,代码来源:OAuthClientCredentialsTokenResponder.cs

示例6: Respond

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

			var jsonDocument = Database.Get(docId, GetRequestTransaction(context));
			if(jsonDocument == null)
			{
				context.SetStatusToNotFound();
				return;
			}

			var deserializeXNode = JsonConvert.DeserializeXNode(jsonDocument.DataAsJson.ToString(Formatting.None), "doc");
			context.Response.ContentType = "text/xml";
			context.Write(deserializeXNode.ToString(SaveOptions.None));
		}
开发者ID:kmaclean,项目名称:Kalahari.Resort,代码行数:16,代码来源:Class1.cs

示例7: Respond

		public override void Respond(IHttpContext context)
		{
			context.Response.AddHeader("ETag", typeof (ClientAccessPolicy).FullName);
			context.Response.SetPublicCachability();
			context.Response.ContentType = "text/xml";
			context.Write(@"<?xml version='1.0' encoding='utf-8'?>
<access-policy>
 <cross-domain-access>
   <policy>
	 <allow-from http-methods='*' http-request-headers='*'>
	   <domain uri='*' />
	 </allow-from>
	 <grant-to>
	   <resource include-subpaths='true' path='/' />
	 </grant-to>
   </policy>
 </cross-domain-access>
</access-policy>");
		}
开发者ID:JPT123,项目名称:ravendb,代码行数:19,代码来源:ClientAccessPolicy.cs

示例8: Respond

		public override void Respond(IHttpContext context)
		{
			var match = urlMatcher.Match(context.GetRequestUrl());
			var index = match.Groups[1].Value;
			switch (context.Request.HttpMethod)
			{
				case "GET":
					if (string.IsNullOrEmpty(index) == false && index != "/")
					{
						context.SetStatusToBadRequest();
						context.WriteJson(new
						{
							Error = "Cannot GET from a specific transformer but got a request for: " + index.Substring(0)
						});
						return;
					}

					var namesOnlyString = context.Request.QueryString["namesOnly"];
					bool namesOnly;
					RavenJArray indexes;
					if (bool.TryParse(namesOnlyString, out namesOnly) && namesOnly)
						indexes = Database.GetTransformerNames(context.GetStart(), context.GetPageSize(Database.Configuration.MaxPageSize));
					else
						indexes = Database.GetTransformers(context.GetStart(), context.GetPageSize(Database.Configuration.MaxPageSize));
					context.WriteJson(indexes);
					break;
				case "PUT":
					var data = context.ReadJsonObject<TransformerDefinition>();
					if (data == null || string.IsNullOrEmpty(data.TransformResults))
					{
						context.SetStatusToBadRequest();
						context.Write("Expected json document with 'TransformResults' property");
						return;
					}
					context.SetStatusToCreated("/transformers");
					context.WriteJson(new { Transfomer = Database.PutTransform(index, data) });
					break;
			}
		}
开发者ID:samueldjack,项目名称:ravendb,代码行数:39,代码来源:Transformers.cs

示例9: Put

		private void Put(IHttpContext context, string index)
		{
			if (index.StartsWith("Raven/", StringComparison.InvariantCultureIgnoreCase))
			{
				context.SetStatusToForbidden();
				context.WriteJson(new
				{
					Url = context.Request.RawUrl,
					Error = "Builtin indexes cannot be modified, attempt to modifiy index '" + index + "' was rejected"
				});
				return;
			}
			var data = context.ReadJsonObject<IndexDefinition>();
			if (data.Map == null)
			{
				context.SetStatusToBadRequest();
				context.Write("Expected json document with 'Map' property");
				return;
			}
			context.SetStatusToCreated("/indexes/" + index);
			context.WriteJson(new { Index = Database.PutIndex(index, data) });
		}
开发者ID:nathanpalmer,项目名称:ravendb,代码行数:22,代码来源:Index.cs

示例10: DispatchRequest

        private void DispatchRequest(IHttpContext ctx)
        {
            if (AssertSecurityRights(ctx) == false)
                return;

            foreach (var requestResponder in RequestResponders)
            {
                if (requestResponder.WillRespond(ctx))
                {
                    requestResponder.Respond(ctx);
                    return;
                }
            }
            ctx.SetStatusToBadRequest();
            if (ctx.Request.HttpMethod == "HEAD")
                return;
            ctx.Write(
                @"
            <html>
            <body>
            <h1>Could not figure out what to do</h1>
            <p>Your request didn't match anything that Raven knows to do, sorry...</p>
            </body>
            </html>
            ");
        }
开发者ID:kenegozi,项目名称:ravendb,代码行数:26,代码来源:HttpServer.cs

示例11: DispatchRequest

		private bool DispatchRequest(IHttpContext ctx)
		{
			SetupRequestToProperDatabase(ctx);

			CurrentOperationContext.Headers.Value = new NameValueCollection(ctx.Request.Headers);

			CurrentOperationContext.Headers.Value[Constants.RavenAuthenticatedUser] = "";
			CurrentOperationContext.User.Value = null;
			if (ctx.RequiresAuthentication &&
				requestAuthorizer.Authorize(ctx) == false)
				return false;

			try
			{
				RecordRequest(ctx);
				OnDispatchingRequest(ctx);

				if (DefaultConfiguration.HttpCompression)
					AddHttpCompressionIfClientCanAcceptIt(ctx);

				HandleHttpCompressionFromClient(ctx);

				

				// Cross-Origin Resource Sharing (CORS) is documented here: http://www.w3.org/TR/cors/
				AddAccessControlHeaders(ctx);
				if (ctx.Request.HttpMethod == "OPTIONS")
					return false;

				foreach (var requestResponderLazy in RequestResponders)
				{
					var requestResponder = requestResponderLazy.Value;
					if (requestResponder.WillRespond(ctx))
					{
						requestResponder.Respond(ctx);
						return requestResponder.IsUserInterfaceRequest;
					}
				}
				ctx.SetStatusToBadRequest();
				if (ctx.Request.HttpMethod == "HEAD")
					return false;
				ctx.Write(
					@"
<html>
	<body>
		<h1>Could not figure out what to do</h1>
		<p>Your request didn't match anything that Raven knows to do, sorry...</p>
	</body>
</html>
");
			}
			finally
			{
				try
				{
					CurrentOperationContext.Headers.Value = new NameValueCollection();
					CurrentOperationContext.User.Value = null;
					currentDatabase.Value = DefaultResourceStore;
					currentConfiguration.Value = DefaultConfiguration;
				}
				catch
				{
					// this can happen during system shutdown
				}
			}
			return false;
		}
开发者ID:csainty,项目名称:ravendb,代码行数:67,代码来源:HttpServer.cs

示例12: GetIndexSource

        private void GetIndexSource(IHttpContext context, string index)
        {
            var viewGenerator = Database.IndexDefinitionStorage.GetViewGenerator(index);
            if (viewGenerator == null)
            {
                context.SetStatusToNotFound();
                return;
            }

            context.Write(viewGenerator.SourceCode);
        }
开发者ID:925coder,项目名称:ravendb,代码行数:11,代码来源:Index.cs

示例13: Respond

		public override void Respond(IHttpContext context)
		{
			if (context.Request.ContentLength > MaxOAuthContentLength)
			{
				context.SetStatusToBadRequest();
				context.WriteJson(new { error = "invalid_request", error_description = "Content length should not be over " + MaxOAuthContentLength + " bytes" });
				return;
			}

			if (context.Request.ContentLength == 0)
			{
				RespondWithChallenge(context);
				return;
			}

			string requestContents;
			using (var reader = new StreamReader(context.Request.InputStream))
				requestContents = reader.ReadToEnd();

			var requestContentsDictionary = OAuthHelper.ParseDictionary(requestContents);
			var rsaExponent = requestContentsDictionary.GetOrDefault(OAuthHelper.Keys.RSAExponent);
			var rsaModulus = requestContentsDictionary.GetOrDefault(OAuthHelper.Keys.RSAModulus);
			if (rsaExponent == null || rsaModulus == null || 
				!rsaExponent.SequenceEqual(OAuthServerHelper.RSAExponent) || !rsaModulus.SequenceEqual(OAuthServerHelper.RSAModulus))
			{
				RespondWithChallenge(context);
				return;
			}

			var encryptedData = requestContentsDictionary.GetOrDefault(OAuthHelper.Keys.EncryptedData);
			if(string.IsNullOrEmpty(encryptedData))
			{
				RespondWithChallenge(context);
				return;
			}

			var challengeDictionary = OAuthHelper.ParseDictionary(OAuthServerHelper.DecryptAsymmetric(encryptedData));
			var apiKeyName = challengeDictionary.GetOrDefault(OAuthHelper.Keys.APIKeyName);
			var challenge = challengeDictionary.GetOrDefault(OAuthHelper.Keys.Challenge);
			var response = challengeDictionary.GetOrDefault(OAuthHelper.Keys.Response);

			if (string.IsNullOrEmpty(apiKeyName) || string.IsNullOrEmpty(challenge) || string.IsNullOrEmpty(response))
			{
				RespondWithChallenge(context);
				return;
			}

			var challengeData = OAuthHelper.ParseDictionary(OAuthServerHelper.DecryptSymmetric(challenge));
			var timestampStr = challengeData.GetOrDefault(OAuthHelper.Keys.ChallengeTimestamp);
			if(string.IsNullOrEmpty(timestampStr))
			{
				RespondWithChallenge(context);
				return;
			}
			
			var challengeTimestamp = OAuthServerHelper.ParseDateTime(timestampStr);
			if (challengeTimestamp + MaxChallengeAge < SystemTime.UtcNow || challengeTimestamp > SystemTime.UtcNow)
			{
				// The challenge is either old or from the future 
				RespondWithChallenge(context);
				return;
			}

			var apiKeyTuple = GetApiKeySecret(apiKeyName);
			if (apiKeyTuple == null)
			{
				context.SetStatusToUnauthorized();
				context.WriteJson(new { error = "unauthorized_client", error_description = "Unknown API Key" });
				return;
			}
			var apiSecret = apiKeyTuple.Item1;
			if (string.IsNullOrEmpty(apiKeyName))
			{
				context.SetStatusToUnauthorized();
				context.WriteJson(new { error = "unauthorized_client", error_description = "Invalid API Key" });
				return;
			}

			var expectedResponse = OAuthHelper.Hash(string.Format(OAuthHelper.Keys.ResponseFormat, challenge, apiSecret));
			if (response != expectedResponse)
			{
				context.SetStatusToUnauthorized();
				context.WriteJson(new { error = "unauthorized_client", error_description = "Invalid challenge response" });
				return;
			}

			var token = apiKeyTuple.Item2;
			context.Write(token.Serialize());
		}
开发者ID:synhershko,项目名称:ravendb,代码行数:89,代码来源:OAuthApiKeyResponder.cs

示例14: DispatchRequest

		private bool DispatchRequest(IHttpContext ctx)
		{
			if (AssertSecurityRights(ctx) == false)
			    return false;

			RecordRequestHeaders(ctx);

			if (Configuration.HttpCompression)
				AddHttpCompressionIfClientCanAcceptIt(ctx);

			foreach (var requestResponder in RequestResponders)
			{
				if (requestResponder.WillRespond(ctx))
				{
					requestResponder.Respond(ctx);
				    return requestResponder is RavenUI || requestResponder is RavenRoot || requestResponder is Favicon;
				}
			}
			ctx.SetStatusToBadRequest();
            if (ctx.Request.HttpMethod == "HEAD")
                return false;
			ctx.Write(
				@"
<html>
    <body>
        <h1>Could not figure out what to do</h1>
        <p>Your request didn't match anything that Raven knows to do, sorry...</p>
    </body>
</html>
");
		    return true;
		}
开发者ID:Inferis,项目名称:ravendb,代码行数:32,代码来源:HttpServer.cs

示例15: TryGetFacetsFromString

		private bool TryGetFacetsFromString(IHttpContext context, string index, out Etag etag, out List<Facet> facets,
		                                    string facetsJson)
		{
			etag = GetFacetsEtag(facetsJson, index);

			facets = JsonConvert.DeserializeObject<List<Facet>>(facetsJson);

			if (facets == null || !facets.Any())
			{
				context.SetStatusToBadRequest();
				context.Write("No facets found in request body");
				return false;
			}
			return true;
		}
开发者ID:samueldjack,项目名称:ravendb,代码行数:15,代码来源:Facets.cs


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