【发布时间】:2018-04-27 03:17:43
【问题描述】:
我有一个使用 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 的响应消息结果。
Here you see the result that is returned with status code 400
但是当我在浏览器中收到错误时,状态码已经改变
Here you see the status code that is returned
从最后一张图中可以看出,处理异常的内容在开始,但已包含默认错误消息并且状态代码已被覆盖。
我遇到的问题是,即使我从 webconfig 中删除了自定义错误消息,消息也是一样的。这是可以覆盖的一些默认行为吗?我错过了什么重要的东西吗?
【问题讨论】:
标签: c# asp.net asp.net-web-api