我们正在做一些 azure 商店集成,其资源提供程序代码要求我们使用 xml 作为返回格式化程序。然而,我们只想将 XML 与 Azure 内容一起使用,而保留默认的 JSON 格式化程序。
那么,有谁知道如何强制特定控制器/方法的 Web api 始终返回 xml,而不会在应用程序启动时干扰全局格式化程序?
使用 MVC 4.5 和代码主要基于https://github.com/MetricsHub/AzureStoreRP https://github.com/MetricsHub/AzureStoreRP,我只是将 Web API 内容移至我们自己的服务中,并修改数据层以使用我们的后端而不是它所具有的实体框架后端。
如果您希望始终从特定操作发回 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)