Skip to content
Snippets Groups Projects
Commit 24607490 authored by snemeckayova's avatar snemeckayova
Browse files

Add ResponseFormatMiddleware

parent b7537438
No related branches found
No related tags found
2 merge requests!46Milestone-2,!38Add ResponseFormatMiddleware
Pipeline #
......@@ -13,6 +13,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
......
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml;
public class ResponseFormatMiddleware
{
private readonly RequestDelegate _next;
public ResponseFormatMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
var originalBodyStream = context.Response.Body;
using var responseBody = new MemoryStream();
context.Response.Body = responseBody;
await _next(context);
context.Response.Body.Seek(0, SeekOrigin.Begin);
var responseText = await new StreamReader(context.Response.Body).ReadToEndAsync();
context.Response.Body.Seek(0, SeekOrigin.Begin);
context.Response.Body = originalBodyStream;
if (context.Request.Query.TryGetValue("format", out var formatValue) && formatValue.ToString().Equals("xml", StringComparison.OrdinalIgnoreCase))
{
context.Response.ContentType = "application/xml";
await context.Response.WriteAsync(ConvertJsonToXml(responseText));
}
else
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(responseText);
}
}
private string ConvertJsonToXml(string json)
{
try
{
JToken parsedJson = JToken.Parse(json);
if (parsedJson is JArray) json = $"{{\"Root\": {json}}}";
var doc = JsonConvert.DeserializeXmlNode(json, "Root");
if (doc == null) return "<error>Unable to convert JSON to XML; null document</error>";
using var stringWriter = new StringWriter();
using var xmlTextWriter = new XmlTextWriter(stringWriter);
doc.WriteTo(xmlTextWriter);
return stringWriter.ToString();
}
catch
{
return "<error>Unable to convert JSON to XML</error>";
}
}
}
......@@ -102,8 +102,8 @@ app.UseHttpsRedirection();
app.UseAuthorization();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseMiddleware<ResponseFormatMiddleware>();
app.MapControllers();
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment