标题或多或少说明了一切。
我正在尝试将 JSON MediaTypeFormatter 配置为每条路由的行为不同。
具体来说,我的 WebAPI 中有两条路由映射到同一个 Controller 。
每条路由都执行相同的操作并返回相同的数据,但出于与现有消费者向后可比性的原因,它们的输出格式必须略有不同。
我可以在 Controller 中放置一些代码来确定请求是来自旧路由还是新路由,并相应地更改格式化程序。
我还可以在需要时使用 ActionFilter 来更改格式化程序。
然而,我想知道是否有一种方法可以在每个路由级别配置格式化程序,因为这是我的 API 行为不同的抽象级别。这可以在路由配置点或委托(delegate)处理程序中。
有什么建议么?
最佳答案
我不完全确定你的两个 JSON 有多大不同,以及你到底在用它们做什么,但如果你问我,我会在格式化程序中做:
public class MyJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
private IHttpRouteData _route;
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
{
_route = request.GetRouteData();
return base.GetPerRequestFormatterInstance(type, request, mediaType);
}
public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (_route.Route.RouteTemplate.Contains("legacy"))
{
//here set the SerializerSettings for non standard JSON
//I just added NullValueHandling as an example
this.SerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
}
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
然后,您将用这个替换默认的 JsonMEdiaTypeFormatter。
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new MyJsonMediaTypeFormatter());
在 Web API 中,您可以拥有
DelegatingHandler
仅在特定路线上运行,但从 Formatters
开始就没有意义了集合是全局的,因此即使在路由范围的处理程序中也没有必要在运行时修改它。
关于asp.net - Web API 中的每个路由格式化程序配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14313241/