.NetCore自定义WebAPI返回Json的格式大小写的三种方式

.NetCore的Controller/WebAPI可以帮我们将返回结果自动转换为Json格式给前台,而且可以*设定格式(大写、小写、首字母大写等),我总结了三种方法,对应三种灵活度,供大家参考

(一)通过Startup.cs设置项目级别的格式

  在项目Startup.cs中增加如下配置:

services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); 

 

 

       默认为保持原样,也可设定为CamelCasePropertyNamesContractResolver(),即首字母小写的驼峰格式。

       本身是没有将属性全部小写的方法,我这里提供一个参考,大家可以自定义想要的格式:

 

 public class LowercaseContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
    {
        protected override string ResolvePropertyName(string propertyName)
        {
            return propertyName.ToLower();
        }
    }

 

(二)设置Controller/WebAPI级别的统一格式转换,这里用到了ActionFilterAttribute,扩展出一个CustomActionJsonFormatAttribute标签

public class CustomActionJsonFormatAttribute : ActionFilterAttribute
    {
        private Type _ContractResolver { get; set; }
        public CustomActionJsonFormatAttribute(Type ContractResolver)
        {
            _ContractResolver = ContractResolver;
        }
        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {var jsonResult = (JsonResult)actionExecutedContext.Result;
                jsonResult.SerializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = Activator.CreateInstance(_ContractResolver) as IContractResolver
                };

                actionExecutedContext.Result = jsonResult;
        }
    }

使用时在Controller/WebAPI中添加如下代码即可,即可以在class层面添加,也可以在Action上添加:

[CustomActionJsonFormat(typeof(LowercaseContractResolver))]

public IActionResult EntityInfo([Required]string entityid) { ... }

 

(三)在代码返回的时候设置JsonResult,这个是最灵活但也最麻烦的方式:

 return new JsonResult(new Entity
                    {
                        EntityId = entityid,
                        Name = entityType.Name,
                        OrganizationId = Permission.getCurrentUserOrg().ORG_GID
                    }, new JsonSerializerSettings
                    {
                        ContractResolver = new LowercaseContractResolver()
                    });

 

.NetCore自定义WebAPI返回Json的格式大小写的三种方式

上一篇:题解——Acwing.340 通信线路


下一篇:深入delphi编程理解之消息(三)发送消息函数的一般应用实例