dotnet core 实现 IActionResult

实现 IActionResult , 只需要记住 Response 有一个 WriteAsync 扩展方法即可

    public class JsonResult<T> : IActionResult
    {
        private T _data;

        public JsonResult(T data)
        {
            _data = data;
        } 

        public Task ExecuteResultAsync(ActionContext context)
        {
            HttpResponse response = context.HttpContext.Response;
            response.ContentType = $"{context.HttpContext.Request.ContentType}; charset=utf-8";

            string json = string.Empty;
            if (this._data != null)
            {
                json = JsonConvert.SerializeObject(_data);
            }

            return Task.FromResult(response.WriteAsync(json));
        }
    }

posted on 2020-11-09 15:19  爱上键盘的蜗牛  阅读(1148)  评论(0编辑  收藏  举报

导航