且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core WebApi 返回统一格式参数(Json 中 Null 替换为空字符串)

更新时间:2022-03-27 18:12:30

业务场景:

统一返回格式参数中,如果包含 Null 值,调用方会不太好处理,需要替换为空字符串,示例:

{
    "response":{
        "code":200,
        "msg":"Remote service error",
        "result":null
    }
}

替换为:

{
    "response":{
        "code":200,
        "msg":"Remote service error",
        "result":""
    }
}

具体实现:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public class WebApiResultMiddleware : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.HttpContext.Request.Path.HasValue)
        {
            if (context.HttpContext.Request.Path.Value.ToLower().IndexOf(".inside.") < 0)
            {
                if (context.Result is FileContentResult || context.Result is EmptyResult)
                {
                    return;
                }
                if (context.Result is ObjectResult)
                {
                    var objectResult = context.Result as ObjectResult;
                    var settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new NullToEmptyStringResolver(),
                        DateFormatString = "yyyy-MM-dd HH:mm"
                    };
                    context.Result = new JsonResult(new { data = objectResult.Value }, settings);
                }
                else
                {
                    context.Result = new ObjectResult(new { data = new { } });
                }
            }
        }
    }
}

public class NullToEmptyStringResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return type.GetProperties()
                .Select(p => {
                    var jp = base.CreateProperty(p, memberSerialization);
                    jp.ValueProvider = new NullToEmptyStringValueProvider(p);
                    return jp;
                }).ToList();
    }
}

public class NullToEmptyStringValueProvider : IValueProvider
{
    PropertyInfo _MemberInfo;
    public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
    {
        _MemberInfo = memberInfo;
    }

    public object GetValue(object target)
    {
        object result = _MemberInfo.GetValue(target);
        if (result == null) result = "";
        return result;

    }

    public void SetValue(object target, object value)
    {
        _MemberInfo.SetValue(target, value);
    }
}

本文转自田园里的蟋蟀博客园博客,原文链接:http://www.cnblogs.com/xishuai/p/asp-net-core-webapi-json-convert-empty-string-instead-of-null.html,如需转载请自行联系原作者