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

标签 c# .net asp.net-mvc asp.net-web-api

我已经为我的 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/

相关文章:

c# - Nancy Self Host 使用 Razor View 的空白响应

c# - 禁止用户在未登录的情况下访问页面/URL

c# - 如何判断一个网址是不是内网网址?

.net - 最新的 Dapper VS Entity Framework 6 性能注意事项

c# - ASP.NET 5 代码分析器推荐

c# - 响应式框架 (RX) 和异步处理事件

.net - 为什么 .NET 中没有 XML 可序列化字典?

c# - 基于数据类型的模型验证

javascript - 如何在 ASP.NET MVC 中的存储库上执行函数?

asp.net-mvc - Ninject 注册每个请求