Web API中的每路径格式化程序配置

Gav*_*orn 6 asp.net asp.net-web-api

标题或多或少都说明了一切.我正在尝试配置JSON MediaTypeFormatter以使每个路由的行为不同.

具体来说,我的WebAPI中有两条路由映射到同一个控制器.每条路线执行相同的操作并返回相同的数据,但出于与现有消费者向后兼容的原因,它们必须略微区别地输出格式.

我可以在Controller中放入一些代码,以确定请求是在传统路由还是新路由中进入,并相应地更改格式化程序.

我还可以使用ActionFilter来更改所需的格式化程序.

然而,我想知道是否有一种方法可以在每个路由级别配置格式化程序,因为这是我的API行为不同的抽象级别.这可以是路径配置点,也可以是代理处理程序.

有什么建议?

Fil*_*p W 7

我不完全确定你的两个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您将使用此替换默认的JsonMEdiaTypeFormatter.

    config.Formatters.RemoveAt(0);
    config.Formatters.Insert(0, new MyJsonMediaTypeFormatter());
Run Code Online (Sandbox Code Playgroud)

在Web API中,您可以DelegatingHandler只在特定路由上运行,但这并不真正有意义,因为Formatters集合是全局的,因此即使从路由范围的处理程序中也没有必要在运行时修改它.

  • 您可以使用每个控制器的配置(通过* IControllerConfiguration * http://blogs.msdn.com/b/jmstall/archive/2012/05/11/per-controller-configuration-in-webapi.aspx)并注册此“自定义”格式器,仅适用于适用于该控制器的一个控制器。这样,核心应用程序仍然使用默认格式化程序,但是具有更多要求的一个控制器使用特定的格式化程序。 (2认同)