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

内容纲要

继承 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
            {
            ... ...
            };
        }
点赞

发表评论

邮箱地址不会被公开。 必填项已用*标注

You must enable javascript to see captcha here!