gpt4 book ai didi

c# - .net Core webapi 2(非 mvc)的 HttpResponseException/IHttpActionResponse 的等价物

转载 作者:IT王子 更新时间:2023-10-29 04:38:37 25 4
gpt4 key购买 nike

当我阅读有关响应请求和处理错误的 webapi 时,一切都基于:

IHttpActionResult
HttpResponseException

但是当你创建一个 .net 核心 webapi 项目时,这些是不可用的。我可以找到 IActionResult,这似乎是等价的?

但我正在兜圈子试图找出一个非常简单的事情,即如何处理 .net 核心 webapi 中的错误,因为 HttpResponseException 不可用。我的印象是所有带有“http”的东西都只适用于完整的 MVC 应用程序。

我只想返回一个错误,肯定很简单......

最佳答案

IActionResult 等同于 IHttpActionResult,如您所建议的。这是 ASP.NET Core MVC 中所谓的 MVC 和 Web API 整合的一部分。

至于HttpResponseException,这在ASP.NET Core中已经被完全移除。有一个有趣的 issue在 GitHub 上围绕这个问题,David Fowler 解释了为什么会这样:

Just the classic, "we don't want people using exceptions for control flow" paradigm. People did things like use it from within their business logic which is all sorts of wrong. I can't speak to the performance issues because I haven't measured but throwing an exception that is meant to be caught to get some data is worse than just returning that result.

建议的替代方法是使用各种 IActionResult 实现来创建 JSON 响应、返回错误等。同样,从这个问题来看:

My suggestion would be to have the action method return IActionResult (or the async variation).

The reason that both IActionResult and object are supported is that they each suit different purposes and different styles. For some of the simplest cases, it's nice to use object, but it isn't powerful at all. For full control, there's IActionResult, which follows the well-known "command pattern."

The IActionResult pattern allows the controller to explicitly state what should happen as a result of the action: some kind of error code, a redirect, a serialized data object, a rendered view, etc.

如果您希望在 Controller 之外处理错误,您可能会受益于阅读 docs关于这个主题,它详细介绍了使用中间件或过滤器进行错误处理。在评论中,有一个指向 tutorial 的链接。更详细地解释了错误处理的某些方面。

为了完整起见,这里是中间件方法教程中的代码:

app.UseExceptionHandler(
options => {
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace }";
await context.Response.WriteAsync(err).ConfigureAwait(false);
}
});
}
);

还有关于 IExceptionFilter 方法的更多详细信息,但我不会在这里重复所有内容。

关于c# - .net Core webapi 2(非 mvc)的 HttpResponseException/IHttpActionResponse 的等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47142142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com