我希望对不同的路由或控制器使用不同的JSON输出Formatters。默认和自定义json输出格式化程序。
Startup.cs
services.AddControllers(options =>
{
options.RespectBrowserAcceptHeader = true;
options.OutputFormatters.Add(new CustomJsonMediaFormatter());
});CustomJsonMediaFormatter
public class CustomJsonMediaFormatter : TextOutputFormatter
{
public JsonMediaFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/vnd.XYZ+json"));
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}
protected override bool CanWriteType(Type type)
{
return true;
}
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
// my code
}
}控制器A
[ApiController]
[Produces("application/vnd.XYZ+json")]
public class AController : BaseController
{
[HttpGet]
public async Task<IActionResult> Get()
{
// return an object
}
}控制器B
[ApiController]
[Produces("application/json")]
public class BController : BaseController
{
[HttpGet]
public async Task<IActionResult> Get()
{
// return an object
}
}当我用邮递员向-- Cotroller发送请求时,它没有使用我的自定义输出格式化程序。它仍然使用默认的JSON输出格式化程序。
它似乎接受了列表中的第一个JSON输出格式化程序。我试图清除输出格式化程序列表并添加自定义json格式化程序。然后,它总是使用自定义格式化程序。
对于自定义输出格式化程序,我要做的是:根据配置,从不允许用户查看的对象中移除一些字段。但只适用于某些API控制器,而不是全部。
发布于 2021-04-14 13:14:38
我找到解决办法了。重写函数CanWriteResult。从上下文中我们得到内容类型
public override bool CanWriteResult(OutputFormatterCanWriteContext context)
{
return context.ContentType == "application/vnd.XYZ+json";
}再加上@JohnD关于格式化程序的答案,它是完美的!
services.AddControllers(options =>
{
options.RespectBrowserAcceptHeader = true;
options.OutputFormatters.Insert(0, new CustomJsonMediaFormatter());
});发布于 2021-04-13 07:20:53
如果您查看他们的文档,您将看到他们正在列表的开头插入客户格式化程序。https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/custom-formatters?view=aspnetcore-5.0#how-to-configure-mvc-to-use-a-custom-formatter
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
options.InputFormatters.Insert(0, new VcardInputFormatter());
options.OutputFormatters.Insert(0, new VcardOutputFormatter());
});
}这使我相信格式化程序的执行顺序很重要,很可能在检查自定义内容接受类型之前执行默认的json命令。
尝试将DI更新为:
services.AddControllers(options =>
{
options.RespectBrowserAcceptHeader = true;
options.OutputFormatters.Insert(0, new CustomJsonMediaFormatter());
});https://stackoverflow.com/questions/67069902
复制相似问题