我们正在运行一个 Web API 站点,它将用于多种用途:
我创建了一个基于 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/