c# - 如何处理 asp.net core 中的异常 "Invalid file signature"?

标签 c# asp.net-core .net-core asp.net-core-mvc entity-framework-core

我使用的是 .txt 文件而不是 excel 文件,所以我应该收到 400 错误,但我收到了 500 错误。我想捕获异常并发送带有适当响应正文的 400 响应代码。

[Route("file/")]
[AuthorizeFunction(AuthFunctions.Schema.Create)]
[HttpPost]
[ResponseType(typeof(Schema))]
public async Task<IActionResult> Create([FromBody] Guid fileId)
{
     var result = await _SchemaService.Create(fileId);
     return Created("GetSchema", new { id = result.Id }, result);
}

最佳答案

您可以使用此代码来捕获特定错误

[Route("file/")]
[AuthorizeFunction(AuthFunctions.Schema.Create)]
[HttpPost]
[ResponseType(typeof(Schema))]
public async Task<IActionResult> Create([FromBody] Guid fileId)
{
     try {
         var result = await _SchemaService.Create(fileId);
         return Created("GetSchema", new { id = result.Id }, result);
     }
     catch (Exception exc){
       if (exc.GetType().FullName == "Your_Exception_Name") 
       {
          // Check your exception name here
       }
   }
}

catch(Exception ex)
{
  if(ex.InnerException is ExceptionInstance)// exception instance type you want to check
  {

  }
}

更新

您可以只使用 catch(Exception ex) 处理一般异常,然后返回 BadRequest()

catch(Exception ex)
{
  return BadRequest();
}

关于c# - 如何处理 asp.net core 中的异常 "Invalid file signature"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57772905/

相关文章:

c# - HttpWebRequest 的并发限制

c# - 寻找最佳线环绕宽度以最大化垂直相同值邻居的数量

c# - 等待 N 个异步方法完成时是否有标准模式可遵循?

ssl - 在 .Net Core 控制台应用程序中生成受信任的自签名证书

c# - 如何更改 Visual Studio Code 中的默认构建输出目录

c# - 流利的断言 : Approximately compare a classes properties

c# - 从文件系统返回图像

asp.net-core - _context.SaveChanges() 有效但等待 _context.SaveChangesAsync() 无效

asp.net-core - .Net Core 运行时环境 (KRE) bin 文件夹中的程序集的用途是什么?

c# - BackgroundService 任务未在 .NET Core 通用主机中的单独线程上运行