ASP.NET Core WebApi 返回统一格式参数(Json 中 Null 替换为空字符串)
发布日期:2021-09-08 15:09:09 浏览次数:0 分类:技术文章

业务场景:

统一返回格式参数中,如果包含 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,如需转载请自行联系原作者

上一篇:4.3. rpm - RPM Package Manager
下一篇:AjaxPro使用Session出错(AjaxPro "Session"引发了"System.NullReferenceException"类型的异常)