Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# &引用;“未处理”;ASP.NETCore3.1中的异常_C#_Asp.net Core - Fatal编程技术网

C# &引用;“未处理”;ASP.NETCore3.1中的异常

C# &引用;“未处理”;ASP.NETCore3.1中的异常,c#,asp.net-core,C#,Asp.net Core,我的日志文件中有一个异常。问题是我的Startup.Configure()方法中有一个全局异常处理程序: 事实上,这是一个很好的选择。因此,异常被处理。如何禁止将此消息放入日志文件 谢谢大家! ERROR|Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware|An unhandled exception has occurred while executing the request. Microsoft.AspNetCore.S

我的日志文件中有一个异常。问题是我的Startup.Configure()方法中有一个全局异常处理程序:

事实上,这是一个很好的选择。因此,异常被处理。如何禁止将此消息放入日志文件

谢谢大家!

ERROR|Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware|An unhandled exception has occurred while executing the request. Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Request body too large.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.OnReadStarting()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.TryStart()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.ReadAsyncInternal(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory`1 buffer, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.WebUtilities.BufferedReadStream.EnsureBufferedAsync(Int32 minCount, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.DrainAsync(Stream stream, ArrayPool`1 bytePool, Nullable`1 limit, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.WebUtilities.MultipartReader.ReadNextSectionAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.Features.FormFeature.InnerReadFormAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.ModelBinding.FormValueProviderFactory.AddValueProviderAsync(ValueProviderFactoryContext context)
   at Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.CreateAsync(ActionContext actionContext, IList`1 factories)
   at Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.TryCreateAsync(ActionContext actionContext, IList`1 factories)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)```
ERROR | Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware |执行请求时发生未经处理的异常。Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException:请求正文太大。
位于Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(请求拒绝原因)
位于Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.OnReadStarting()
在Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.TryStart()上
位于Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.ReadAsyncInternal(CancellationToken CancellationToken)
位于Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(内存`1缓冲区,CancellationToken CancellationToken)
在Microsoft.AspNetCore.WebUtilities.BufferedReadStream.EnsureBufferedAsync(Int32 minCount,CancellationToken CancellationToken)
位于Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.ReadAsync(字节[]缓冲区、Int32偏移量、Int32计数、CancellationToken CancellationToken)
在Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.DrainAsync(Stream Stream,ArrayPool`1 bytePool,Nullable`1 limit,CancellationToken CancellationToken)
位于Microsoft.AspNetCore.WebUtilities.MultipartReader.ReadNextSectionAsync(CancellationToken CancellationToken)
在Microsoft.AspNetCore.Http.Features.FormFeature.InnerReadFormAsync(CancellationToken CancellationToken)上
位于Microsoft.AspNetCore.Mvc.ModelBinding.FormValueProviderFactory.AddValueProviderAsync(ValueProviderFactoryContext)
位于Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.CreateAsync(ActionContext ActionContext,IList`1工厂)
位于Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.TryCreateAsync(ActionContext ActionContext,IList`1工厂)
在Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.c_uuDisplayClass0_0.d.MoveNext()中
---来自引发异常的上一个位置的堆栈结束跟踪---
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g_u等待| 13_0(ControllerActionInvoker invoker,Task lastTask,State next,Scope Scope,Object State,Boolean isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|24_0(ResourceInvoker invoker、Task lastTask、State next、Scope Scope、Object State、Boolean isCompleted)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed上下文)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(状态和下一步、范围和范围、对象和状态、布尔值和isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()中
---来自引发异常的上一个位置的堆栈结束跟踪---
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u waiting | 17|0(ResourceInvoker invoker,Task Task,IDisposable作用域)
位于Microsoft.AspNetCore.Routing.EndpointMiddleware.g_uwaitRequestTask | 6_0(端点、任务请求任务、ILogger记录器)
位于Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext上下文)
在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文)中
位于Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext上下文)
在Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g|u waiting|6|0(ExceptionHandlerMiddleware中间件,HttpContext上下文,任务任务)```

我建议您不要禁用日志错误,因为这是发现用户问题的主要方法之一。 无论如何,如果您想禁用错误日志记录,您可以从配置中执行。默认配置文件为“appsettings.json”文件:

这将抑制来自Microsoft或主机的任何错误消息。
请注意,在开发环境中还使用了“appsettings.Development.json”文件,您可能希望在其中禁用日志记录。可靠地记录异常是全局异常处理程序实际上可以做的一件事。之后,它应该总是让异常继续下去。对于日志记录,它必须捕获广泛的异常,这意味着它将捕获致命的异常,而这些异常应该总是被释放。全局处理程序是解决任何问题的最晚方式。要正确地记录任何东西可能都太晚了,因为到那时大多数东西都已经超出了范围

要知道如何正确处理它,我们首先需要对它进行分类。我使用这个分类系统:

BadHttpRequestException
看起来像是一个愚蠢的异常。那些你永远不应该忽视的,理想情况下永远不会抓住的。您应该修复的那些

然而,当我们处理网络时,有可能是一个外生的或令人烦恼的例外。如果它是其中之一,你应该抓住它,尽可能靠近它被扔的地方,并且尽可能精确。还要给调用代码一些提示,说明出现了问题,因此预期结果不存在。我曾经为一个复制的TryParse编写过这个示例:

//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).

bool TryParse(string input, out int output){
  try{
    output = int.Parse(input);
  }
  catch (Exception ex){
    if(ex is ArgumentNullException ||
      ex is FormatException ||
      ex is OverflowException){
      //these are the exceptions I am looking for. I will do my thing.
      output = 0;
      return false;
    }
    else{
      //Not the exceptions I expect. Best to just let them go on their way.
      throw;
    }
  }

  //I am pretty sure the Exception replaces the return value in exception case. 
  //So this one will only be returned without any Exceptions, expected or unexpected
  return true;
}
解析中令人烦恼的部分?它们就在那里被捕获,并通过布尔返回进行通信。我必须捕获大量或三倍的处理代码,因此我尽了最大努力进行
is
检查,以便稍后进行筛选


对于一般体面的实践,我确实有。与上面的分类一起,它是我所有异常处理决策的核心。

错误处理程序的一个非常常见的操作就是准确地记录它,为什么要忽略它?BadHttpRequestException听起来像是一个愚蠢的例外,根据这种分类:那些你应该修复/避免的,从未捕获的(例外
"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft": 6,
    "Microsoft.Hosting.Lifetime": 6
  }
}
//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).

bool TryParse(string input, out int output){
  try{
    output = int.Parse(input);
  }
  catch (Exception ex){
    if(ex is ArgumentNullException ||
      ex is FormatException ||
      ex is OverflowException){
      //these are the exceptions I am looking for. I will do my thing.
      output = 0;
      return false;
    }
    else{
      //Not the exceptions I expect. Best to just let them go on their way.
      throw;
    }
  }

  //I am pretty sure the Exception replaces the return value in exception case. 
  //So this one will only be returned without any Exceptions, expected or unexpected
  return true;
}