Fork me on GitHub

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

相关博文:ASP.NET Core WebApi 返回统一格式参数

业务场景:

统一返回格式参数中,如果包含 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);
    }
}

参考资料:

posted @ 2017-11-01 16:31  田园里的蟋蟀  阅读(9067)  评论(6编辑  收藏  举报