我正在运行WebAPI OData v4服务,并且我不希望发出空值。例如,当我请求User
对象,以下则返回:防止在WebAPI OData v4服务中发出空值
"value": [
{
"FirstName": "John",
"LastName": "Smith",
"EmailAddress": "[email protected]",
"PasswordHash": null,
"PhoneNumber": "11234567890",
"Website": null,
"Id": "dac9706a-8497-404c-bb5a-ca1024cf213b"
}
由于PasswordHash
和Website
字段是空值,我希望他们不包括在输出中。我试着在应用程序的注册块以下行,但他们没有工作:
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
下面是注册方法的全部内容。我正在使用Newtonsoft Json包来处理JSON序列化。
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "UploadComplete",
routeTemplate: "UploadFiles/Complete",
defaults: new { controller = "UploadFiles", action = "Complete" }
);
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Address>("Addresses");
builder.EntitySet<Assignment>("Assignments");
builder.EntitySet<Course>("Courses");
builder.EntitySet<File>("Files");
builder.EntitySet<UploadFile>("UploadFiles");
builder.EntitySet<Organization>("Organizations");
builder.EntitySet<Submission>("Submissions");
builder.EntitySet<Term>("Terms");
builder.EntitySet<User>("Users");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
// Neither of these lines work.
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
}
我认为你可以从ODataEntityTypeSerializer.cs派生,并从ODataEntry中的'Properties'中移除“null”属性。 –