我正在运行WebAPI OData v4服务,并且我不希望发出空值。例如,当我请求一个User对象时,将返回以下内容:

"value": [
{
  "FirstName": "John",
  "LastName": "Smith",
  "EmailAddress": "[email protected]",
  "PasswordHash": null,
  "PhoneNumber": "11234567890",
  "Website": null,
  "Id": "dac9706a-8497-404c-bb5a-ca1024cf213b"
}


由于PasswordHashWebsite字段为空,我希望它们不包含在输出中。我已经在应用程序的Register块中尝试了以下几行,但是它们都不起作用:

config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;


下面是Register方法的全部内容。我正在使用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;
    }

最佳答案

感谢Brian Rogers向我指出了正确的方向,我最终像这样覆盖了ODataEntityTypeSerializer

public override ODataEntry CreateEntry(SelectExpandNode selectExpandNode, EntityInstanceContext entityInstanceContext)
{
    ODataEntry entry = base.CreateEntry(selectExpandNode, entityInstanceContext);

    // Remove any properties which are null.
    List<ODataProperty> properties = new List<ODataProperty>();
    foreach (ODataProperty property in entry.Properties)
    {
        if (property.Value != null)
        {
            properties.Add(property);
        }
    }

    entry.Properties = properties;
    return entry;
}


然后,我使用RaghuRam-Nadiminti's answer中的代码来实现CustomSerializerProvider类,然后可以在Register中使用该类。

关于c# - 防止在WebAPI OData v4服务中发出空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33192231/

10-12 12:55