gpt4 book ai didi

c# - Web API 2 服务 - 如何在状态中返回异常消息

转载 作者:行者123 更新时间:2023-11-30 12:40:25 25 4
gpt4 key购买 nike

是否可以在 Web API 2 中直接在响应的 Status 中返回异常消息?

例如,如果我正在编写一个 WCF 服务(而不是 Webi API),我可以遵循 this tutorial直接返回异常消息作为响应状态的一部分:

enter image description here

此处,Web 服务不在 Response 中返回任何数据,而是在 Status Description 中直接返回错误消息。

这正是我希望我的 Web API 服务在发生异常时执行的操作,但我不知道该怎么做。

大多数建议建议使用如下代码,但随后错误消息将始终在单独的响应字符串中返回,而不是作为状态的一部分。

例如,如果我要使用这段代码:

public IHttpActionResult GetAllProducts()
{
try
{
// Let's get our service to throw an Exception
throw new Exception("Something went wrong");

return Ok(products);
}
catch (Exception ex)
{
return new System.Web.Http.Results.ResponseMessageResult(
Request.CreateErrorResponse((HttpStatusCode)500,
new HttpError("Something went wrong")));
}
}

...然后它返回一个通用的 500 消息,异常以 JSON 字符串返回。

enter image description here

有谁知道如何修改 Web API 函数(返回 IHttpActionResult 对象)来执行此操作?

最佳答案

您可以注册一个自定义的全局过滤器来处理所有异常。像这样的东西:

public class CatchAllExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(context.Exception.Message)
};
}
}

您需要在 WebApiConfig.cs 中注册它,方法是:

config.Filters.Add(new CatchAllExceptionFilterAttribute());

每次系统中出现未处理的异常时都会命中此过滤器,并将 http 响应设置为异常消息。您还可以检查不同类型的异常并相应地更改您的响应,例如:

    public override void OnException(HttpActionExecutedContext context)
{
if(context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented)
{
Content = new StringContent("Method not implemented.")
};
}
else
{
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(context.Exception.Message)
};
}

}

关于c# - Web API 2 服务 - 如何在状态中返回异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823986/

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