自定义结果类通过实现IActionResult接口控制响应,如TextResult返回指定编码的纯文本;2. 在控制器中直接返回自定义结果实例;3. 可创建ApiResponse<T>统一API结构,配合ApiJsonResult<T>输出JSON;4. 建议封装重复逻辑,注意异步操作、正确设置Content-Type与状态码,优先考虑ActionResult<T>或中间件简化场景。

在 ASP.NET Core 中创建自定义结果类,主要是通过继承 IActionResult 接口来实现。这样你可以完全控制响应的生成过程,比如返回特殊格式的数据、文件、重定向逻辑,或者组合多种响应行为。
定义一个类实现 IActionResult,并在 ExecuteResultAsync 方法中编写响应逻辑。
例如:创建一个返回纯文本并指定编码的自定义结果:
public class TextResult : IActionResult
{
private string _text;
private string _contentType;
private Encoding _encoding;
public TextResult(string text, string contentType = "text/plain", Encoding encoding = null)
{
_text = text;
_contentType = contentType;
_encoding = encoding ?? Encoding.UTF8;
}
public async Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = _contentType;
response.Headers.Add("Content-Encoding", _encoding.WebName);
var textBytes = _encoding.GetBytes(_text);
await response.Body.WriteAsync(textBytes, 0, textBytes.Length);
}
}在控制器方法中直接返回自定义结果实例。
[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
[HttpGet("hello")]
public IActionResult GetHello()
{
return new TextResult("Hello, 自定义结果!", "text/plain", Encoding.UTF8);
}
}有时需要统一返回结构(如包含 code、message、data 的 API 格式),可以创建通用包装结果。
public class ApiResponse<T>
{
public int Code { get; set; }
public string Message { get; set; }
public T Data { get; set; }
public ApiResponse(int code, string message, T data)
{
Code = code;
Message = message;
Data = data;
}
public static ApiResponse<T> Success(T data) =>
new ApiResponse<T>(200, "Success", data);
public static ApiResponse<T> Error(string message) =>
new ApiResponse<T>(500, message, default);
}配合自定义结果返回结构化 JSON:
public class ApiJsonResult<T> : IActionResult
{
private ApiResponse<T> _response;
public ApiJsonResult(ApiResponse<T> response)
{
_response = response;
}
public async Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/json";
var json = JsonSerializer.Serialize(_response);
await response.WriteAsync(json);
}
}控制器中使用:
[HttpGet("data")]
public IActionResult GetData()
{
var data = new { Id = 1, Name = "Test" };
var apiResponse = ApiResponse<object>.Success(data);
return new ApiJsonResult<object>(apiResponse);
}自定义结果类适合封装重复响应逻辑,但要注意以下几点:
基本上就这些。自定义结果类提供了高度灵活的响应控制能力,适用于需要精细输出控制的场景。
以上就是ASP.NET Core 中的自定义结果类如何创建?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号