zoukankan      html  css  js  c++  java
  • 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);
        }
    }
    

    参考资料:

  • 相关阅读:
    android Logger 一二三
    深挖android low memory killer
    ios CoreBluetooth 警告 is being dealloc'ed while pending connection
    iOS 国际化多语言设置 xcode7
    iOS 控制单个控制器旋转
    ios 开发 收起键盘的小技巧
    xcode ___gxx_personality_v0" 编译错误
    xcode6 AsynchronousTesting 异步任务测试
    xcode6 framework missing submodule xxx 警告
    iOS AVCaptureVideoDataOutputSampleBufferDelegate 录制视频
  • 原文地址:https://www.cnblogs.com/xishuai/p/asp-net-core-webapi-json-convert-empty-string-instead-of-null.html
Copyright © 2011-2022 走看看