停止在WebAPI中显示完整的堆栈跟踪

34

WebAPI发生意外错误时,用户会看到整个堆栈跟踪。

我认为显示整个堆栈跟踪是不安全的。

如何停止向我的用户显示完整的跟踪?默认行为是什么?

只有友好的消息,比如说单独的内部服务器错误就足够了,对吗?

有任何想法吗?

<?xml version="1.0"?>
<Error>
  <Message>An error has occurred.</Message>
  <ExceptionMessage>The method or operation is not implemented.</ExceptionMessage>
  <ExceptionType>System.NotImplementedException</ExceptionType>
  <StackTrace>   at MyCompany.BLL.RequirementOfService.Employee1.Employee1Service.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.BAL.RequirementOfService\Employee1\Employee1Service.cs:line 37
   at MyCompany.BLL.RequirementOfService.RequirementOfServiceBLL.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.BAL.RequirementOfService\RequirementOfServiceBLL.cs:line 76
   at MyCompany.RequirementOfService.Windsor.RequirementOfServiceProvider.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.RequirementOfService\Windsor\RequirementOfServiceProvider.cs:line 47
   at MyCompany.RequirementOfService.RequirementOfService.Controllers.RequirementOfServiceController.Post(RequirementOfServiceDTO RequirementOfServiceDTO) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.RequirementOfService\RequirementOfService\Controllers\RequirementOfServiceController.cs:line 87
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.&lt;&gt;c__DisplayClass10.&lt;GetExecutor&gt;b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Web.Http.Controllers.ApiControllerActionInvoker.&lt;InvokeActionAsyncCore&gt;d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
2个回答

59

有没有一种方法可以仅抑制堆栈跟踪,但保留消息不变?这样做似乎会删除所有异常信息。 - Molibar

11

对于那些只想屏蔽StackTrace而不是丢弃重要错误提示的人,您可以实现一个ExceptionFilter。

您可以分两步完成:

  1. 按以下方式编写过滤器:

    using System.Web.Http.Filters;
    using System.Net;
    using System.Net.Http;
    
    public class MyExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var request = context.Request;
            var response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, context.Exception.Message);
            var content = (System.Net.Http.ObjectContent<System.Web.Http.HttpError>)response.Content;
    
            var errorValues = (System.Web.Http.HttpError)content.Value;
            errorValues["ExceptionMessage"] = context.Exception.Message;
            errorValues["ExceptionType"] = context.Exception.GetType().Name;
            if (context.ActionContext != null)
            {
                errorValues["ActionName"] = context.ActionContext.ActionDescriptor.ActionName;
                errorValues["ControllerName"] = context.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
            }
    
            context.Response = response;
        }
    }
    
  2. 让 WebApi 使用您的 ExceptionFilter:

  3. public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new MyExceptionFilterAttribute());
    

你将获得这个:

{
  "Message": "Your exception is here!",
  "ExceptionMessage": "Your exception is here!",
  "ExceptionType": "Exception",
  "ActionName": "MyAction",
  "ControllerName": "MyController"
}

更多信息请访问:https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接