asp.net-web-api - 在 ASP.Net Web API 中,如何更改特定 Controller 或操作的默认格式化程序

标签 asp.net-web-api mediatypeformatter

我们正在运行一个 Web API 站点,它将用于多种用途:

  • 在开发客户端中,例如我们构建的 iPhone 应用程序,它将主要使用 JSON。
  • 普通用户通过 RSS 客户端,将其添加到他们最喜欢的 RSS 阅读器(例如 Flipboard)中。

  • 我创建了一个基于 this link 的自定义 RSS 2.0并在 WebApiConfig 中配置
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.Add(new SyndicationMediaTypeFormatter());
    

    它接受 application/rss+xml 和 application/atom+xml 的接受头。

    用户通常将 RSS 提要粘贴到他们的 rss 客户端中,而不知道任何有关 header 的信息——因此我需要一些默认为 RSS 的路由。

    但是,这是棕地开发,并且 json 提要已在使用中,目前是默认设置,我无法更改整个站点的默认格式化程序而不会对现有的开发人员客户产生不利影响。

    我可以使它成为特定 Controller 的默认格式化程序,而不是整个站点的默认格式化程序吗?

    最佳答案

    您可以使用 IControllerConfiguration定义每个 Controller 的特定配置..

    This是描述此场景的示例。你可以快速看看这个接口(interface)应该如何使用超过here (来自样本)。

    自定义配置的示例是:

    public class CustomControllerConfigAttribute : Attribute, IControllerConfiguration
    {
        public void Initialize(HttpControllerSettings controllerSettings, 
                               HttpControllerDescriptor controllerDescriptor)
        {
            // Register an additional plain text media type formatter
            controllerSettings.Formatters.Add(new PlainTextBufferedFormatter());
        }
    }
    

    PlainTextBufferedFormatter 的来源如果你很好奇。

    关于asp.net-web-api - 在 ASP.Net Web API 中,如何更改特定 Controller 或操作的默认格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22464772/

    相关文章:

    .net-assembly - 从哪里引用丢失的程序集 (System.Net.Http.Formatting)?

    c# - Core 2.1 APIVersioning 操作歧义

    asp.net - IHttpControllerFactory 在哪里?

    c# - 使用 HttpClient 通过 AttributeRouting 在 URL 中发送日期

    c# - .NET Core RedirectToAction 不重定向

    javascript - 使用 Web Api Controller 参数映射 AngularJs 查询字符串

    asp.net-mvc-4 - 自定义 MediaTypeFormatter,为什么是 IKeyValueModel 而不是我的模型类型?

    asp.net-mvc - 如何为 ASP.NET 4.5 Web API 创建 MultipartFormFormatter