在维持默认JSON的同时在某些Web API控制器上强制xml返回 [英] force xml return on some web api controllers while maintaining default JSON

查看:144
本文介绍了在维持默认JSON的同时在某些Web API控制器上强制xml返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在做一些天蓝色的商店集成,其资源提供者代码要求我们使用xml作为返回格式化程序.但是,我们只希望将XML与Azure东西一起使用,而不必使用默认的JSON格式化程序.

We are doing some azure store integration and its resource provider code requires us to use xml as the return formatter. However we only want to use XML with the Azure stuff and leave the default JSON formatter alone.

那么,有谁知道您可以如何强制特定控制器/引擎的Web api始终返回xml,而不会在应用程序启动时与全局格式化程序发生冲突?

So, does anyone know how you can force the web api for specific controllers/methoods to always return xml without messing with the global formatters at application start?

使用MVC 4.5和很大程度上基于> https://github.com/MetricsHub/AzureStoreRP ,我只是将Web api内容移到了我们自己的服务中,并修改了数据层以使用我们的后端而不是它拥有的实体框架后端.

Working with MVC 4.5 and code based largely off of https://github.com/MetricsHub/AzureStoreRP, I simply moved the web api stuff into our own services and modified the data layer to use our backend versus the entity framework backend it has.

推荐答案

如果您希望始终从特定操作中发回Xml,则可以执行以下操作:

If you like to always send back Xml from a specific action, you could just do the following:

public HttpResponseMessage GetCustomer(int id)
{
    Customer customer = new Customer() { Id  =1, Name = "Michael" };

    //forcing to send back response in Xml format
    HttpResponseMessage resp = Request.CreateResponse<Customer>(HttpStatusCode.OK, value: customer,
        formatter: Configuration.Formatters.XmlFormatter);

    return resp;
}

您只能拥有特定于某些控制器的格式化程序.这可以通过称为Per-Controller Configuration的功能来实现:

You can have formatters specific to certain controllers only. This can be achieved by a feature called Per-Controller Configuration:

[MyControllerConfig]
public class ValuesController : ApiController


[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MyControllerConfigAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
    {
        // yes, this instance is from the global formatters
        XmlMediaTypeFormatter globalXmlFormatterInstance = controllerSettings.Formatters.XmlFormatter;

        controllerSettings.Formatters.Clear();

        // NOTE: do not make any changes to this formatter instance as it reference to the instance from the global formatters.
        // if you need custom settings for a particular controller(s), then create a new instance of Xml formatter and change its settings.
        controllerSettings.Formatters.Add(globalXmlFormatterInstance);
    }
}

这篇关于在维持默认JSON的同时在某些Web API控制器上强制xml返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆