实现 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));
}
}