/// <inheritdoc /> public void SendJson(object item, bool asText = false, bool?prettyPrint = null, bool ignoreNulls = false) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (!BinaryCache.TryGet(item, out var body)) { Formatting _prettyPrint; if (prettyPrint == null) { _prettyPrint = Admin.Settings._PrettyPrint ? Formatting.Indented : Formatting.None; } else { _prettyPrint = prettyPrint.Value ? Formatting.Indented : Formatting.None; } var stream = Providers.Json.SerializeStream(item, _prettyPrint, ignoreNulls); body = stream.ToArray(); BinaryCache.Cache(item, body); } _SendBinary(body, asText, 0, body.Length); }
/// <inheritdoc /> public void SendResult(IResult result, TimeSpan?timeElapsed = null, bool writeHeaders = false, bool disposeResult = true) { try { switch (Status) { case WebSocketStatus.Open: break; case var other: throw new InvalidOperationException($"Unable to send results to a WebSocket with status '{other}'"); } if (result is WebSocketUpgradeSuccessful) { return; } var serialized = result.IsSerialized ? (ISerializedResult)result : result.Serialize(); if (serialized is Content content && content.IsLocked) { throw new InvalidOperationException("Unable to send a result that is already assigned to a Websocket streaming " + "job. Streaming results are locked, and can only be streamed once."); } var foundCached = BinaryCache.TryGet(serialized, out var body); if (!foundCached && serialized.Body?.CanRead == false) { throw new InvalidOperationException($"Unable to send a disposed result over Websocket '{Id}'. To send the " + "same result multiple times, set 'disposeResult' to false in the call to " + "'SendResult()'."); } var info = result.Headers.Info; var errorInfo = result.Headers.Error; var timeInfo = ""; if (timeElapsed != null) { timeInfo = $" ({timeElapsed.Value.TotalMilliseconds} ms)"; } var tail = ""; if (info != null) { tail += $". {info}"; } if (errorInfo != null) { tail += $" (see {errorInfo})"; } _SendText($"{result.StatusCode.ToCode()}: {result.StatusDescription}{timeInfo}{tail}"); if (writeHeaders) { SendJson(result.Headers, true); } if (body == null && serialized.Body != null && (!serialized.Body.CanSeek || serialized.Body.Length > 0)) { body = serialized.Body.ToByteArray(); } if (body != null) { if (!foundCached) { BinaryCache.Cache(serialized, body); } SendBinary(body, 0, body.Length); } } finally { if (disposeResult) { result.Dispose(); } } }