2013-07-22 4 views
7

Wir tun etwas Azure-Store-Integration und seine Ressource Provider-Code erfordert, dass wir XML als Return-Formatierer verwenden. Wir möchten jedoch nur XML mit dem Azure-Material verwenden und den Standard-JSON-Formatierer alleine lassen.erzwingen xml Rückkehr auf einigen Web-API-Controller unter Beibehaltung der Standard-JSON

Also, weiß jemand, wie Sie die Web API für bestimmte Controller/Methoods zwingen können, immer xml zurückgeben, ohne mit den globalen Formatierern beim Start der Anwendung zu stören?

Mit MVC 4.5 und Code basierend weitgehend von https://github.com/MetricsHub/AzureStoreRP, bewegte ich einfach die Web-API-Zeug in unsere eigenen Dienste und modifizierte die Datenschicht, um unser Back-End im Vergleich zu den Entity-Framework-Backend es hat.

Antwort

16

Wenn Sie immer wieder gerne XML-Daten aus einer bestimmten Aktion zurück senden, können Sie nur Folgendes tun:

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

Sie können nur Formatierer für bestimmte Controller haben. Dies kann durch ein Merkmal Per-Controller Configuration genannt erreicht werden:

[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); 
    } 
} 
+0

Das zweite Beispiel ist das, was ich suche. Das ist großartig Danke! – danatcofo

+0

Das ist, was ich suche. Danke Kiran !!!! –

Verwandte Themen