C# ASP.NET Web API处理的异常返回错误的状态代码

C# ASP.NET Web API处理的异常返回错误的状态代码,c#,asp.net,asp.net-web-api,C#,Asp.net,Asp.net Web Api,我有一个使用ASP.NET Web API 2.0的项目,该API中有一个方法引发异常: public void TestMethod() { throw new Exception("Error40001"); } 当抛出此异常时,我创建了一个处理程序来处理这类事情: public class APIExceptionHandler : ExceptionHandler { public override void Handle(Excepti

我有一个使用ASP.NET Web API 2.0的项目,该API中有一个方法引发异常:

    public void TestMethod()
    {
        throw new Exception("Error40001");
    }
当抛出此异常时,我创建了一个处理程序来处理这类事情:

public class APIExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var rm = Language.Error.ResourceManager;
        string message = rm.GetString(context.Exception.Message);
        string detailed = "";
        try
        {
            detailed = rm.GetString(context.Exception.Message + "Detailed");
        }
        catch
        {
            if (String.IsNullOrEmpty(detailed))
            {
                detailed = message;
            }
        }
        HttpStatusCode code = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), context.Exception.Message.Replace("Error", "").Substring(0, 3));

        context.Result = new ResponseMessageResult(context.Request.CreateResponse(code,
            new ErrorInformation() { Message = message, DetailedMessage = detailed }));
    }
}

public class ErrorInformation
{
    public string Message { get; set; }
    public string DetailedMessage { get; set; }
}
我遇到的问题是,当我收到这个错误时,它不再是我设置的相同状态代码。处理程序拾取它并创建一个响应消息结果,错误代码为400

但当我在浏览器中收到错误时,状态代码已更改

从上一张图片中可以看出,已处理异常的内容位于开始处,但已包含默认错误消息,并且状态代码已被覆盖


我遇到的问题是,即使我从webconfig中删除自定义错误消息,消息也是一样的。这是可以覆盖的默认行为吗?我是否遗漏了一些重要内容?

而不是设置
上下文。结果使用以下代码

throw new HttpResponseException(context.Request.CreateResponse(code,
            new ErrorInformation() { Message = message, DetailedMessage = detailed }));

这在处理程序中不起作用,但如果我用throw httpresponseexception替换testmethod中的throw异常,它似乎完全绕过了处理程序,然后就起作用了。你知道为什么这样做有效而处理程序不起作用吗?