消防培训系统服务器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.9 KiB

2 years ago
using Microsoft.AspNetCore.Mvc.Formatters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
public class RawJsonOutputFormatter : TextOutputFormatter
{
public RawJsonOutputFormatter()
{
this.SupportedMediaTypes.Add("application/json");
this.SupportedEncodings.Add(Encoding.UTF8);
this.SupportedEncodings.Add(Encoding.Unicode);
}
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (selectedEncoding == null)
throw new ArgumentNullException(nameof(selectedEncoding));
using (var writer = context.WriterFactory(context.HttpContext.Response.Body, selectedEncoding))
{
if (context.Object is string str)
{
writer.Write(str);
}
else if (context.Object is List<string> list)
{
writer.Write('[');
var index = 0;
var last = list.Count - 1;
for (var i = 0; i < list.Count; ++i)
{
writer.Write(list[i]);
if(index != last)
writer.Write(',');
}
writer.Write(']');
}
else
throw new InvalidOperationException();
await writer.FlushAsync();
}
}
protected override bool CanWriteType(Type type)
{
return type == typeof(string)
|| type == typeof(List<string>);
}
}
}