private string GetBodyAsString(Request request) { if (request.Body == null) { return string.Empty; } if (request.Headers.ContainsKey("Content-Type")) { var contentType = request.Headers["Content-Type"]; if (contentType == "text/plain" || contentType == "application/json" || contentType == "application/json; charset=utf-8") { var bodyAsString = Encoding.UTF8.GetString(request.Body); if (contentType == "application/json") { try { return $"<pre>{JObject.Parse(bodyAsString).ToString(Formatting.Indented)}</pre>"; } catch (Exception ex) { return $"Invalid JSON: {ex.Message}"; } } return bodyAsString; } if (contentType == "application/x-www-form-urlencoded") { var bodyAsString = Encoding.UTF8.GetString(request.Body); return $"<pre>{string.Join("<br />", bodyAsString.Split('&'))}</pre>"; } } return "Unsupported Content-Type"; }
public async Task<ActionResult> Receive(string id, string url) { var request = new Request { ReceptacleId = id, ReceivedAtUtc = DateTime.UtcNow, Url = Request.GetDisplayUrl(), Headers = Request.Headers.ToDictionary(d => d.Key, d => d.Value.ToString()), Method = Request.Method, }; var contentLength = Request.ContentLength ?? 0; if (contentLength > 0 && Request.ContentType != null) { var bodyBuffer = new byte[contentLength]; await Request.Body.ReadAsync(bodyBuffer, 0, bodyBuffer.Length); request.Body = bodyBuffer; } var coll = Database.GetCollection<Request>("Requests"); coll.Insert(request); return Ok(); }