29 lines
1.0 KiB
C#
29 lines
1.0 KiB
C#
using Microsoft.AspNetCore.Mvc.Formatters;
|
|
using System.Text.Json;
|
|
using System.Text;
|
|
|
|
namespace ServiceHost.MiddleWare;
|
|
|
|
public class ConditionalJsonOutputFormatter : TextOutputFormatter
|
|
{
|
|
private readonly JsonSerializerOptions _options;
|
|
|
|
public ConditionalJsonOutputFormatter(JsonSerializerOptions options)
|
|
{
|
|
_options = options;
|
|
SupportedMediaTypes.Add("application/json");
|
|
SupportedEncodings.Add(System.Text.Encoding.UTF8);
|
|
}
|
|
|
|
public override bool CanWriteResult(OutputFormatterCanWriteContext context)
|
|
{
|
|
var path = context.HttpContext.Request.Path;
|
|
return path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
|
|
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
|
|
{
|
|
var response = context.HttpContext.Response;
|
|
await JsonSerializer.SerializeAsync(response.Body, context.Object, context.ObjectType ?? context.Object?.GetType() ?? typeof(object), _options);
|
|
}
|
|
} |