ASP.NET Core 自定义 IActionResult 返回 Json ,首字母小写等

2021年8月21日 4075点热度 0人点赞 0条评论
内容目录

继承 IActionResult:

    public class ResponseResult<TData> : IActionResult
    {
        /// <summary>
        /// 状态码
        /// </summary>
        public int Code { get; set; }

        /// <summary>
        /// 响应信息
        /// </summary>
        public string Msg { get; set; }

        /// <summary>
        /// 响应数据
        /// </summary>
        public TData Result { get; set; }

        /// <summary>
        /// 响应内容类型
        /// </summary>
        protected const string contentTypeString = "application/json; charset=utf-8";

        /// <summary>
        /// 对响应结果进行格式化
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual async Task ExecuteResultAsync(ActionContext context)
        {
            context.HttpContext.Response.ContentType = contentTypeString;
            var executor = context.HttpContext.RequestServices.GetRequiredService<IActionResultExecutor<JsonResult>>();
            var jsonResult = new JsonResult(this);
            await executor.ExecuteAsync(context, jsonResult);
        }
    }

使用:

        public async Task<IActionResult> SetActiveState(string accountId, bool active)
        {
        ... ... 
            return new ResponseResult
            {
            ... ...
            };
        }

痴者工良

高级程序员劝退师

文章评论