我需要根据查询参数选择OutputFormatter
。如何做到这一点?我正在从.NET Framework WebApi
移动到.NET Core WebApi.
.NET Framework WebApi
有DefaultContentNegotiator
类这样做:
public class CustomContentNegotiator : DefaultContentNegotiator
{
public override ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
//Read query from request object and add output formatters below
bindFormatters = new List<MediaTypeFormatter>
{
new ConvertResultRawFormatter(),
new JsonMediaTypeFormatter
{
SerializerSettings =
{
NullValueHandling = NullValueHandling.Ignore
}
}
};
}
return base.Negotiate(type, request, bindFormatters);
}
}
在配置中替换为新格式化的谈判者
config.Services.Replace(typeof(IContentNegotiator), new CustomContentNegotiator());
自定义输出格式化程序对您不起作用吗?阅读此ms文档
从注释来看,真正的问题是,如果URL包含download=inline
参数,如何添加Content-Disposition: inline
标头。这与格式或内容协商无关。
有几种方法可以将标头添加到响应中。其中之一是添加内联中间件,如果存在查询参数,该中间件将添加标头:
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
var download= context.Request.Query["download"];
if (download=="inline")
{
context.Response.Headers.Add("Content-Disposition", "inline");
}
}
}
这会影响的所有路线