2013-07-22 20 views
7

Chúng tôi đang thực hiện tích hợp cửa hàng Azure và mã của nhà cung cấp tài nguyên yêu cầu chúng tôi sử dụng xml làm trình định dạng trả lại. Tuy nhiên, chúng tôi chỉ muốn sử dụng XML với các công cụ Azure và để riêng trình định dạng JSON mặc định. Vì vậy, có ai biết làm thế nào bạn có thể buộc api web cho bộ điều khiển cụ thể/methoods để luôn luôn trở lại xml mà không gây rối với các formatter toàn cầu khi bắt đầu ứng dụng?buộc xml trở lại trên một số bộ điều khiển api trên web trong khi duy trì mặc định JSON

Làm việc với MVC 4.5 và mã chủ yếu là tắt của https://github.com/MetricsHub/AzureStoreRP, tôi chỉ cần di chuyển công cụ api web vào dịch vụ của riêng mình và sửa đổi lớp dữ liệu để sử dụng chương trình phụ trợ của chúng tôi.

Trả lời

16

Nếu bạn muốn luôn luôn gửi lại Xml từ một hành động cụ thể, bạn chỉ có thể làm như sau:

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

Bạn có thể có và định dạng cụ thể để chỉ điều khiển nhất định. Điều này có thể đạt được bằng cách một tính năng gọi 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); 
    } 
} 
+0

Ví dụ thứ hai là những gì tôi đang tìm kiếm. Đó là lời cảm ơn tuyệt vời! – danatcofo

+0

Đây là những gì tôi đang tìm kiếm. Cảm ơn Kiran !!!! –