dan*_*ofo 8 xml asp.net-mvc json formatter asp.net-web-api
我们正在进行一些azure商店集成,其资源提供者代码要求我们使用xml作为返回格式化程序.但是,我们只希望将XML与Azure内容一起使用,并保留默认的JSON格式化程序.
那么,有没有人知道如何强制web api为特定的控制器/方法总是返回xml而不会在应用程序启动时搞乱全局格式化程序?
使用MVC 4.5和基于https://github.com/MetricsHub/AzureStoreRP的代码,我只需将web api内容移动到我们自己的服务中并修改数据层以使用我们的后端与实体框架后端.
Kir*_*lla 17
如果您希望始终从特定操作发回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;
}
Run Code Online (Sandbox Code Playgroud)
您可以只使用特定于某些控制器的格式化程序.这可以通过以下功能实现Per-Controller Configuration:
[MyControllerConfig]
public class ValuesController : ApiController
Run Code Online (Sandbox Code Playgroud)
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3866 次 |
| 最近记录: |