asp.net - Web API 中的每个路由格式化程序配置

标签 asp.net asp.net-web-api

标题或多或少说明了一切。
我正在尝试将 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/

相关文章:

asp.net - 在 IIS 中一次请求上传大文件时的内存使用情况

javascript - 如何从 asp.net 隐藏字段中设置和获取 bool 值

c# - 调用在 Asp.Net 页面中启 Action 业的 oracle 存储过程

c# - 哪种 ResponseType 应该用于 PUT 或 POST 请求的 IHttpActionResult?

c# - 请求的资源不支持 HTTP 方法 'GET'

c# - 使用 SimpleInjector 为 AccountController/ApplicationUserManager 注册 UserStore

c# - 如何在特定位置呈现用户控件子项?

c# - winsock 资源不足

c# - 在 swagger 中为 web api 中的特定版本添加不记名 token 选项

c# - 从客户端应用程序调用 Web API