kri*_*son 11 asp.net asp.net-web-api
我使用常规方法在我的项目中配置Web API,但是,我确实有一个我需要支持的遗留API.
我配置日期时间格式如下:
JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Include,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var converters = jsonFormatter.SerializerSettings.Converters;
converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss" });
Run Code Online (Sandbox Code Playgroud)
这正是我想要的大多数API控制器,但是,对于遗留API,它需要使用旧的MS AJAX格式输出DateTimes,如下所示:
/日期(13453.02亿)/
所以任何人都知道我如何为我的一个API模块指定不同的JSON日期格式化器并保持全局配置的原样?或者任何替代方案,例如每个API的配置都可以.谢谢
Kir*_*lla 11
Web API有一个名为Per-Controller配置的概念,仅适用于像您这样的场景.每个控制器配置使您可以基于每个控制器进行配置.
public class MyConfigAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
// controllerSettings.Formatters is a cloned list of formatters that are present on the GlobalConfiguration
// Note that the formatters are not cloned themselves
controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter);
//Add your Json formatter with the datetime settings that you need here
controllerSettings.Formatters.Insert(0, **your json formatter with datetime settings**);
}
}
[MyConfig]
public class ValuesController : ApiController
{
public string Get(int id)
{
return "value";
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,ValuesController将使用带有日期时间设置的Json格式化程序,但您的其他控制器将使用GlobalConfiguration上的控制器.
归档时间: |
|
查看次数: |
1865 次 |
最近记录: |