gpt4 book ai didi

c# - 客户端没有收到来自 ApiController 的自定义 HttpResponseException

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

我已经为我的 Web API Controller 操作创建了一个异常过滤器,但它似乎没有做任何事情(即使它确实被调用)。

属性

public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
context.Response.Content = new StringContent("My content");
context.Response.ReasonPhrase = "My reason";
}
}

我也试过:

public override void OnException(HttpActionExecutedContext context)
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("The content"),
ReasonPhrase = "The reason"
});
}

Controller

[ExceptionHandler]
public class MyController : ApiController
{
[Route("MyRoute"), HttpGet]
public MyModel Index() {
// code causing exception
}
}

WebApiConfig

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ExceptionHandlerAttribute());
}
}

但是,当发生异常时,客户端会收到:

Exception Message

最佳答案

您需要使用异常过滤器的响应抛出一个 HttpResponseException:

public override void OnException(HttpActionExecutedContext context)
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("The content"),
ReasonPhrase = "The reason"
});
}

这里有关于 how to handle exceptions in Web API 的更多详细信息.

关于c# - 客户端没有收到来自 ApiController 的自定义 HttpResponseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31448620/

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