更新时间:2023-02-16 23:19:49
这是一个例子:
public class TestResult
{
public Exception Exception { get; set; }
public object Data { get; set; }
}
public class TestActionResult : IActionResult
{
private readonly TestResult _result;
public TestActionResult(TestResult result)
{
_result = result;
}
public async Task ExecuteResultAsync(ActionContext context)
{
var objectResult = new ObjectResult(_result.Exception ?? _result.Data)
{
StatusCode = _result.Exception != null
? StatusCodes.Status500InternalServerError
: StatusCodes.Status200OK
};
await objectResult.ExecuteResultAsync(context);
}
}
ObjectResult
是如果您从操作返回非IActionResult
的结果将被转换的类型.它将为您进行内容协商.
ObjectResult
is the type your results are converted if you return a non-IActionResult
from an action. It will do content negotiation for you.
您也可以从 ObjectResult
继承并设置要写入构造函数的状态代码和数据.
You could also inherit from ObjectResult
and setup the status code and data to be written in the constructor.
有关 ASP.NET Core 中的内容协商的更多信息:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting#content-negotiation
More on content negotiation in ASP.NET Core: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting#content-negotiation