本文整理汇总了C#中IHttpContext.WriteJson方法的典型用法代码示例。如果您正苦于以下问题:C# IHttpContext.WriteJson方法的具体用法?C# IHttpContext.WriteJson怎么用?C# IHttpContext.WriteJson使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IHttpContext
的用法示例。
在下文中一共展示了IHttpContext.WriteJson方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Respond
public override void Respond(IHttpContext context)
{
var auth = context.Request.Headers["Authorization"];
if(string.IsNullOrEmpty(auth))
{
context.SetStatusToBadRequest();
context.WriteJson(new
{
Error = "Could not find authorization header"
});
return;
}
if (auth.StartsWith("Bearer") == false)
{
context.SetStatusToBadRequest();
context.WriteJson(new
{
Error = "Authorization header does not starts with Bearer"
});
return;
}
context.Response.SetCookie("OAuth-Token", Uri.EscapeDataString(auth));
}
示例2: Respond
public override void Respond(IHttpContext context)
{
var match = urlMatcher.Match(context.GetRequestUrl());
var queue = match.Groups[1].Value;
switch (context.Request.HttpMethod)
{
case "GET":
context.WriteJson(Queues.Statistics(queue));
break;
case "POST":
var metadata = context.Request.Headers.FilterHeaders(isServerDocument: true);
var msgId = Queues.Enqueue(new IncomingMessage
{
Data = context.Request.InputStream.ReadData(),
Queue = queue,
Metadata = metadata,
TimeToLive = metadata.Property("Raven-Time-To-Live") != null
? TimeSpan.FromSeconds(metadata.Value<int>("Raven-Time-To-Live"))
: TimeSpan.FromMinutes(5)
});
context.WriteJson(new {MsgId = msgId});
break;
}
}
示例3: 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()
});
}
}
示例4: Respond
public override void Respond(IHttpContext context)
{
if (context.User.IsAdministrator() == false)
{
context.SetStatusToUnauthorized();
context.WriteJson(new
{
Error = "Only administrators can look at the server stats"
});
return;
}
if(ResourceStore != DefaultResourceStore)
{
context.SetStatusToBadRequest();
context.WriteJson(new
{
Error = "Admin stats can only be had from the root database"
});
return;
}
context.WriteJson(server.Statistics);
}
示例5: Respond
public override void Respond(IHttpContext context)
{
var parameters = GetParametersFromPath(context.GetRequestUrl(), context.Request.QueryString);
var index = Database.IndexStorage.GetIndexInstance(parameters.IndexName);
if (index == null)
{
context.SetStatusToNotFound();
context.WriteJson(new { Error = "The index " + parameters.IndexName + " cannot be found" });
return;
}
var indexEtag = Database.GetIndexEtag(parameters.IndexName, null);
if (context.MatchEtag(indexEtag))
{
context.SetStatusToNotModified();
return;
}
var result = Database.ExecuteMoreLikeThisQuery(parameters, GetRequestTransaction(context), context.GetPageSize(Database.Configuration.MaxPageSize), context.Request.QueryString.GetValues("include"));
if (context.MatchEtag(result.Etag))
{
context.SetStatusToNotModified();
return;
}
context.Response.AddHeader("ETag", result.Etag.ToString());
context.WriteJson(result.Result);
}
示例6: RespondToAdmin
public override void RespondToAdmin(IHttpContext context)
{
if (EnsureSystemDatabase(context) == false)
return;
var db = context.Request.QueryString["database"];
if(string.IsNullOrWhiteSpace(db))
{
context.SetStatusToBadRequest();
context.WriteJson(new
{
Error = "Compact request requires a valid database parameter"
});
return;
}
var configuration = server.CreateTenantConfiguration(db);
if (configuration == null)
{
context.SetStatusToNotFound();
context.WriteJson(new
{
Error = "No database named: " + db
});
return;
}
server.LockDatabase(db, () =>
SystemDatabase.TransactionalStorage.Compact(configuration));
}
示例7: 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()
}));
}
示例8: Respond
public override void Respond(IHttpContext context)
{
var src = context.Request.QueryString["from"];
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;
}
using (ReplicationContext.Enter())
{
var document = Database.Get(ReplicationConstants.RavenReplicationSourcesBasePath + "/" + src, null);
if (document == null)
{
log.DebugFormat("Got replication last etag request from {0}: [{1}]", src, new SourceReplicationInformation());
context.WriteJson(new SourceReplicationInformation());
}
else
{
var sourceReplicationInformation = document.DataAsJson.JsonDeserialization<SourceReplicationInformation>();
log.DebugFormat("Got replication last etag request from {0}: [{1}]", src, sourceReplicationInformation);
context.WriteJson(sourceReplicationInformation);
}
}
}
示例9: Respond
public override void Respond(IHttpContext context)
{
var principal = context.User;
if (principal == null || principal.Identity == null || principal.Identity.IsAuthenticated == false)
{
context.WriteJson(new
{
Remark = "Using anonymous user",
AnonymousAreAdmins = server.SystemConfiguration.AnonymousUserAccessMode == AnonymousUserAccessMode.Admin
});
return;
}
var windowsPrincipal = principal as WindowsPrincipal;
if (windowsPrincipal != null)
{
context.WriteJson(new
{
Remark = "Using windows auth",
User = windowsPrincipal.Identity.Name,
IsAdmin = windowsPrincipal.IsAdministrator(server.SystemConfiguration.AnonymousUserAccessMode)
});
return;
}
var principalWithDatabaseAccess = principal as PrincipalWithDatabaseAccess;
if (principalWithDatabaseAccess != null)
{
context.WriteJson(new
{
Remark = "Using windows auth",
User = principalWithDatabaseAccess.Identity.Name,
IsAdmin = principalWithDatabaseAccess.IsAdministrator(server.SystemConfiguration.AnonymousUserAccessMode),
principalWithDatabaseAccess.AdminDatabases,
principalWithDatabaseAccess.ReadOnlyDatabases,
principalWithDatabaseAccess.ReadWriteDatabases,
});
return;
}
var oAuthPrincipal = principal as OAuthPrincipal;
if (oAuthPrincipal != null)
{
context.WriteJson(new
{
Remark = "Using OAuth",
User = oAuthPrincipal.Name,
IsAdmin = oAuthPrincipal.IsAdministrator(server.SystemConfiguration.AnonymousUserAccessMode),
oAuthPrincipal.TokenBody,
});
return;
}
context.WriteJson(new
{
Remark = "Unknown auth",
Principal = principal
});
}
示例10: 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 indexEtag = Database.GetIndexEtag(index, null);
if (context.MatchEtag(indexEtag))
{
context.SetStatusToNotModified();
return;
}
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 (distanceTypes == StringDistanceTypes.None)
{
context.SetStatusToBadRequest();
context.WriteJson(new
{
Error = "Suggestion is disabled since you specified the Distance value as 'StringDistanceTypes.None'."
});
return;
}
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;
bool popularity;
if (bool.TryParse(context.Request.QueryString["popularity"], out popularity) == false)
popularity = false;
var query = new SuggestionQuery
{
Distance = distanceTypes,
Field = field,
MaxSuggestions = numOfSuggestions,
Term = term,
Accuracy = accuracy,
Popularity = popularity
};
var suggestionQueryResult = Database.ExecuteSuggestionQuery(index, query);
context.WriteETag(Database.GetIndexEtag(index, null));
context.WriteJson(suggestionQueryResult);
}
示例11: 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;
}
List<DatabaseAccess> authorizedDatabases;
if (!AuthenticateClient.Authenticate(Database, identity.Item1, identity.Item2, out authorizedDatabases))
{
if ((Database == SystemDatabase ||
!AuthenticateClient.Authenticate(SystemDatabase, 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.OAuthTokenKey, new AccessTokenBody
{
UserId = userId,
AuthorizedDatabases = authorizedDatabases
});
context.Write(token.Serialize());
}
示例12: Respond
public override void Respond(IHttpContext context)
{
var target = LogManager.GetTarget<DatabaseMemoryTarget>();
if(target == null)
{
context.SetStatusToNotFound();
context.WriteJson(new
{
Error = "DatabaseMemoryTarget was not registered in the log manager, logs endpoint disabled"
});
return;
}
var database = Database;
if(database == null)
{
context.SetStatusToBadRequest();
context.WriteJson(new
{
Error = "No database found."
});
return;
}
if(database.Name == null)
{
context.SetStatusToBadRequest();
context.WriteJson(new
{
Error = "Database name is null."
});
return;
}
IEnumerable<LogEventInfo> log = target[Database.Name].GeneralLog;
switch (context.Request.QueryString["type"])
{
case "error":
case "warn":
log = target[Database.Name].WarnLog;
break;
}
context.WriteJson(log.Select(x => new
{
x.TimeStamp,
Message = x.FormattedMessage,
x.LoggerName,
Level = x.Level.ToString(),
Exception = x.Exception == null ? null : x.Exception.ToString()
}));
}
示例13: Respond
public override void Respond(IHttpContext context)
{
var dir = SystemDatabase.Configuration.PluginsDirectory;
if (Directory.Exists(dir) == false)
{
context.WriteJson(new PluginsStatus());
return;
}
var plugins = new PluginsStatus { Plugins = Directory.GetFiles(dir,"*.dll").Select(Path.GetFileNameWithoutExtension).ToList() };
context.WriteJson(plugins);
}
示例14: Respond
public override void Respond(IHttpContext context)
{
switch (context.Request.HttpMethod)
{
case "GET":
long documentsCount = 0;
Etag lastDocEtag = Etag.Empty;
Database.TransactionalStorage.Batch(accessor =>
{
lastDocEtag = accessor.Staleness.GetMostRecentDocumentEtag();
documentsCount = accessor.Documents.GetDocumentsCount();
});
lastDocEtag = lastDocEtag.HashWith(BitConverter.GetBytes(documentsCount));
if (context.MatchEtag(lastDocEtag))
{
context.SetStatusToNotModified();
}
else
{
context.WriteHeaders(new RavenJObject(), lastDocEtag);
using (var cts = new CancellationTokenSource())
{
cts.TimeoutAfter(Settings.DatbaseOperationTimeout);
var startsWith = context.Request.QueryString["startsWith"];
if (string.IsNullOrEmpty(startsWith))
context.WriteJson(Database.GetDocuments(context.GetStart(), context.GetPageSize(Database.Configuration.MaxPageSize), context.GetEtagFromQueryString(), cts.Token));
else
context.WriteJson(Database.GetDocumentsWithIdStartingWith(
startsWith,
context.Request.QueryString["matches"],
context.Request.QueryString["exclude"],
context.GetStart(),
context.GetPageSize(Database.Configuration.MaxPageSize),
cts.Token));
}
}
break;
case "POST":
var json = context.ReadJson();
var id = Database.Put(null, Etag.Empty, json,
context.Request.Headers.FilterHeaders(),
GetRequestTransaction(context));
context.SetStatusToCreated("/docs/" + Uri.EscapeUriString(id.Key));
context.WriteJson(id);
break;
}
}
示例15: Respond
public override void Respond(IHttpContext context)
{
switch (context.Request.HttpMethod)
{
case "GET":
long documentsCount = 0;
Guid lastDocEtag = Guid.Empty;
Database.TransactionalStorage.Batch(accessor =>
{
lastDocEtag = accessor.Staleness.GetMostRecentDocumentEtag();
documentsCount = accessor.Documents.GetDocumentsCount();
});
var array = lastDocEtag.ToByteArray().Concat(BitConverter.GetBytes(documentsCount)).ToArray();
using (var md5 = MD5.Create())
{
var hashed = md5.ComputeHash(array);
lastDocEtag = new Guid(hashed);
}
if (context.MatchEtag(lastDocEtag))
{
context.SetStatusToNotModified();
}
else
{
context.WriteHeaders(new RavenJObject(), lastDocEtag);
var startsWith = context.Request.QueryString["startsWith"];
if (string.IsNullOrEmpty(startsWith))
context.WriteJson(Database.GetDocuments(context.GetStart(), context.GetPageSize(Database.Configuration.MaxPageSize), context.GetEtagFromQueryString()));
else
context.WriteJson(Database.GetDocumentsWithIdStartingWith(
startsWith,
context.Request.QueryString["matches"],
context.GetStart(),
context.GetPageSize(Database.Configuration.MaxPageSize)));
}
break;
case "POST":
var json = context.ReadJson();
var id = Database.Put(null, Guid.Empty, json,
context.Request.Headers.FilterHeaders(),
GetRequestTransaction(context));
context.SetStatusToCreated("/docs/" + Uri.EscapeUriString(id.Key));
context.WriteJson(id);
break;
}
}