如果您希望始终从特定操作发送回 Xml,您可以执行以下操作:
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
:
[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);
}
}