force xml return on some web api controllers while maintaining default JSON

前提是你 提交于 2019-12-04 12:05:17

问题


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.

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?

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.


回答1:


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;
}

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);
    }
}


来源:https://stackoverflow.com/questions/17791619/force-xml-return-on-some-web-api-controllers-while-maintaining-default-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!