【发布时间】:2021-01-20 14:40:56
【问题描述】:
我想通过 OData 响应 Owin Self-Host Startup 省略 Web Api 中的 Null 属性/值,以减少内容大小。
我有 112 个控制器从单个抽象 ApiController 类继承,因此使用 CustomDirectRouteProvider。 (不重要)
我正在运行 Framework 4.8,而不是 CORE。
我需要帮助实施与 How to Ignore Null values while serializing OData response 类似的解决方案
我已经阅读了几乎所有关于该主题的帖子,“Stas Natalenko”解决方案似乎适用于 OData v3 及更早版本,但我不确定如何在自托管上为 Odata v4 实施“Chris Schaller”解决方案。
这是我的启动课:
public class CustomDirectRouteProvider : DefaultDirectRouteProvider
{
protected override System.Collections.Generic.IReadOnlyList<IDirectRouteFactory>
GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
{
// inherit route attributes decorated on base class controller's actions
return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>
(inherit: true);
}
}
public class Startup
{
public static void Configuration(IAppBuilder appBuilder)
{
using (var config = new HttpConfiguration())
{
config.EnableSwagger(c => c.SingleApiVersion("v1", "MyAPI"))
.EnableSwaggerUi();
config.MapHttpAttributeRoutes(new CustomDirectRouteProvider());
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.AddODataQueryFilter();
config.Formatters.Clear();
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null)
.EnableDependencyInjection();
config.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter
{
UseDataContractJsonSerializer = false,
SerializerSettings = new JsonSerializerSettings
{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateParseHandling = DateParseHandling.DateTimeOffset,
DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind,
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore
}
});
config.Formatters.Add(new System.Net.Http.Formatting.BsonMediaTypeFormatter());
appBuilder.UseWebApi(config);
};
}
}
【问题讨论】:
-
这是我人生中关于 StackOverFlow 的第一个问题。这些年来我一直很干净facepalm
-
你使用什么版本的
Microsoft.AspNet.WebApi.OData(Nuget)? -
也许是一个长镜头,但是这些设置是否可以在 MvcJsonOptions 中被覆盖? builder.Services.Configure
(opts => opts.SerializerSettings.NullValueHandling...... -
@Julián 最新稳定版 7+
-
不使用 MVC,仅使用 WebApi。为了使其工作,必须“app.UseMVC”或其他东西,然后从 mvc 控制器而不是 api 控制器继承。
标签: c# .net asp.net-web-api odata owin