【发布时间】:2014-01-12 17:57:30
【问题描述】:
您好,我正在 asp.net WebApi 中创建一个异常处理机制,我对如何创建返回的响应消息感到困惑。这是我的代码:
public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Request.CreateErrorResponse(HttpStatusCode.Accepted, new HttpError
{
{ "Message" , "I am error"},
{ "StatusCode" , "20"}
});
}
}
[AllowAnonymous]
[HttpPost]
[Validate]
public IHttpActionResult Register(UserModel userRegistrationModel)
{
throw new AccessDeniedException("message" , new Exception("inner exception"));
}
public class AccessDeniedException : BaseException
{
public AccessDeniedException(string message, Exception exception)
: base(message, exception)
{
}
}
public class BaseException : Exception
{
public BaseException(string message , Exception exception) : base(message , exception)
{
}
}
现在我已经在 myfilter 配置中注册了 ExceptionHandlerAttributed,在调试时我意识到 OnException 方法中的代码运行。
问题是响应是这个:
"readyState": 4,
"responseText": "{\"message\":\"An error has occurred.\",\"exceptionMessage\":\"message\",\"exceptionType\":\"CodeArt.Common.Exceptions.AccessDeniedException\",\"stackTrace\":\" at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\\r\\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()\",\"innerException\":{\"message\":\"An error has occurred.\",\"exceptionMessage\":\"inner exception\",\"exceptionType\":\"System.Exception\",\"stackTrace\":null}}",
"responseJSON": {
"message": "An error has occurred.",
"exceptionMessage": "message",
"exceptionType": "CodeArt.Common.Exceptions.AccessDeniedException",
"stackTrace": " at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()",
"innerException": {
"message": "An error has occurred.",
"exceptionMessage": "inner exception",
"exceptionType": "System.Exception",
"stackTrace": null
}
},
"status": 500,
"statusText": "Internal Server Error"
我不想发送异常堆栈跟踪以及与异常相关的任何其他内容。我只想发送 OnException 方法中的数据集。
我做错了什么?
【问题讨论】:
标签: c# asp.net-web-api