有时上传的文件在C#8中是空的

有时上传的文件在C#8中是空的,c#,angular,asp.net-core,exception,asp.net-web-api,C#,Angular,Asp.net Core,Exception,Asp.net Web Api,我的应用程序允许我上传表单中的文档文件(必填字段)。 在数据库中,我们有一列“Documents”,它存储上传的文件路径。 有时,对于某些用户,用户正在填写表单,当他们单击“保存”按钮时,数据成功插入,但“文档”列中的值为空,上载文件路径中也没有上载文件。在前端,我正在验证(必填字段)文档上载字段,但仍然会向数据库发送一个空值,并且不会在日志文件中引发任何异常 是否有任何方法可以捕获与此相关的异常 'SubmitController.cs' [HttpPost] [Route(&

我的应用程序允许我上传表单中的文档文件(必填字段)。 在数据库中,我们有一列“Documents”,它存储上传的文件路径。 有时,对于某些用户,用户正在填写表单,当他们单击“保存”按钮时,数据成功插入,但“文档”列中的值为空,上载文件路径中也没有上载文件。在前端,我正在验证(必填字段)文档上载字段,但仍然会向数据库发送一个空值,并且不会在日志文件中引发任何异常

是否有任何方法可以捕获与此相关的异常

'SubmitController.cs'

[HttpPost]
        [Route("Add")]
        public string AddRecord([FromBody]ProductionUpload data)
        {
            string recaptcha = string.Empty;

            try
            {
                'Validate the model'
                if (!ModelState.IsValid)
                {
                    throw new Exception("Server-side validation message(s): " +
                                        ModelState.Values.Select(v => v.Errors.Select(e => e.ErrorMessage).Aggregate((a, b) => a + "; " + b))
                                                         .Aggregate((a, b) => a + "; " + b));
                }

                'Validate Recaptcha response'
                if (!ValidateRecaptchaResponse(data.Recaptcha))
                {
                    throw new Exception("Invalid Recaptcha response: " + data.Recaptcha);
                }

                'Save the request to DB'
                data.DateOfSubmission = DateTime.UtcNow;
                _context.ProductionUploads.Add(data);
                _context.SaveChanges();

                data.RegistryNumber = "P" + data.Id.ToString().PadLeft(6, '0');
                _context.SaveChanges();

                recaptcha = data.Recaptcha;
            }
            catch (Exception ex)
            {
                SendExceptionEmail(ex);
                _logger.LogError("{0}\n{1}", ex.Message, ex.StackTrace);
                throw;
            }

            return recaptcha;
        }

        [HttpPost]
        [DisableRequestSizeLimit]
        [Route("Upload")]
        public void UploadDocument()
        {
            List<ProductionUpload> fileData = new List<ProductionUpload>();

            try
            {
                var recaptcha = Request.Form["data"].ToString();
                var files = Request.Form.Files;

                // Validate the document
                if (files.Count > 0)
                {
                    uint maximumDocumentSize = _configuration.GetSection("AppSettings").GetValue<uint>("MaximumDocumentSize");
                    List<FileType> allowedDocumentTypes = _configuration.GetSection("AppSettings:AllowedDocumentTypes").Get<List<FileType>>();

                    var fileExt = Path.GetExtension(files[0].FileName);
                    if (files[0].Length == 0 || files[0].Length > maximumDocumentSize ||
                        (!allowedDocumentTypes.Any(ft => ft.Extension.ToLower() == fileExt.ToLower() && (string.IsNullOrEmpty(ft.ContentType) || ft.ContentType.ToLower() == files[0].ContentType.ToLower()))))
                    {
                        throw new Exception(string.Format("Server-side file validation failure: {0}, {1} bytes, {2} content type", files[0].FileName, files[0].Length, files[0].ContentType));
                    }
                }

                'Validate the cover letter
                if (files.Count > 1)
                {
                    uint maximumCoverLetterSize = _configuration.GetSection("AppSettings").GetValue<uint>("MaximumCoverLetterSize");
                    List<FileType> allowedCoverLetterTypes = _configuration.GetSection("AppSettings:AllowedCoverLetterTypes").Get<List<FileType>>();

                    var fileExt = Path.GetExtension(files[1].FileName);
                    if (files[1].Length == 0 || files[1].Length > maximumCoverLetterSize ||
                        (!allowedCoverLetterTypes.Any(ft => ft.Extension.ToLower() == fileExt.ToLower() && (string.IsNullOrEmpty(ft.ContentType) || ft.ContentType.ToLower() == files[1].ContentType.ToLower()))))
                    {
                        throw new Exception(string.Format("Server-side file validation failure: {0}, {1} bytes, {2} content type", files[1].FileName, files[1].Length, files[1].ContentType));
                    }
                }

                'Get the previously saved Submission from the database'
                ProductionUpload productionUpload = _context.ProductionUploads.SingleOrDefault(sr => sr.Recaptcha == recaptcha);
                if (productionUpload == null || productionUpload.Id == 0)
                {
                    throw new Exception("Invalid Recaptcha response: " + recaptcha);
                }

                'Save the uploaded files'
                string fileUploadPath = _configuration.GetSection("AppSettings").GetValue<string>("FileUploadPath");
                string pathToSave = Path.Combine(fileUploadPath, Guid.NewGuid().ToString());

                if (!Directory.Exists(pathToSave))
                    Directory.CreateDirectory(pathToSave);

                for (int i = 0; i < files.Count; i++)
                {
                    var fileName = Path.GetFileName(files[i].FileName);
                    var localFileName = ReplaceInvalidCharacters(fileName);

                    var dbPath = Path.Combine(pathToSave, localFileName);
                    using (var stream = new FileStream(dbPath, FileMode.Create))
                    {
                        files[i].CopyTo(stream);
                    }

                    if (i == 0)
                    {
                        productionUpload.Documents = dbPath;
                    }
                    else
                    {
                        productionUpload.CoverLetter = dbPath;
                    }
                }

                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                SendExceptionEmail(ex);
                _logger.LogError("{0}\n{1}", ex.Message, ex.StackTrace);
                throw;
            }
        }

'home-component.ts'

ngOnInit() {
    this.requestForm = this.formBuilder.group({
      Id: ['', ''],
      ProducingEntity: [null, Validators.required],
      PartyCode: [null,Validators.required],
      RepresentedBy: [null],
      ContactName: [null, Validators.required],
      Email: [null, [Validators.required, Validators.pattern(this.emailPattern)]],
      ContactNumber: [null, [Validators.required, Validators.pattern(this.phoneNumberPattern)]],
      ReferenceNumber: [null],
      NoticeToProduceNumber: [null, [Validators.required, Validators.pattern(this.ntpPattern)]],
      TrancheNumber: [null, Validators.pattern(this.tranchePattern)],
      ReplacementFiles: [null, Validators.required],
      UploadMaterial: [null, Validators.required],
      Password: [null],
      Description: [null],
      Recaptcha: [null, Validators.required]
    });
    this.requestForm.controls.Id.setValue(0);
  }

HandleDocumentInput(files: FileList) {
    if (files != null && files.length > 0) {
      this.ShowDocumentAlertMessage = false;
      if (!this.ValidateFileSize(files.item(0), this.maxDocumentSize)) {
        this.documentUploader.queue.pop();
        this.DocumentAlertMessageType = 2; // failure
        this.DocumentMessage = "File size must be greater than 0 and cannot exceed 4GB.";
        this.ShowDocumentAlertMessage = true;
        this.documentInput.nativeElement.value = '';
        return;
      }
      if (!this.ValidateFileType(files.item(0), this.allowedDocumentExtensions)) {
        this.documentUploader.queue.pop();
        this.DocumentAlertMessageType = 2; // failure
        this.DocumentMessage = "Files with this extension cannot be uploaded.";
        this.ShowDocumentAlertMessage = true;
        this.documentInput.nativeElement.value = '';
        return;
      }
      this.DocumentFile = files.item(0);
      this.DocumentName = files.item(0).name;
      this.IsDocumentUploaded = true;
      this.documentInput.nativeElement.value = '';
    }
  }

'app-service.ts'

Submit(productionUpload: ProductionUpload) {
    const apiUrl = window.location.href + 'ProductionUpload/Add';
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      }),
      responseType: 'text' as 'json'
    };
    productionUpload.ReplacementFiles = +productionUpload.ReplacementFiles;
    productionUpload.IsDeleted = false;
    productionUpload.IsProcessed = false;
    return this._http.post<string>(apiUrl, productionUpload, httpOptions);
  }

  UploadFile(recaptcha, fileToUpload: File[]) {
    const apiUrl = window.location.href + 'ProductionUpload/Upload';
    const formData: FormData = new FormData();

    if (fileToUpload && fileToUpload.length) 
    {
       fileToUpload.forEach(file => formData.append('files', file));
    }
    formData.append('data', recaptcha)
    return this._http.post(apiUrl, formData);
  }
[HttpPost]
[路线(“添加”)]
公共字符串AddRecord([FromBody]ProductionUpload数据)
{
string recaptcha=string.Empty;
尝试
{
“验证模型”
如果(!ModelState.IsValid)
{
抛出新异常(“服务器端验证消息:”+
ModelState.Values.Select(v=>v.Errors.Select(e=>e.ErrorMessage).Aggregate((a,b)=>a+“;”+b))
.合计((a,b)=>a+“;”+b));
}
“验证Recaptcha响应”
如果(!validateRecaptCharResponse(data.Recaptcha))
{
抛出新异常(“无效的Recaptcha响应:+data.Recaptcha”);
}
'将请求保存到数据库'
data.DateOfSubmission=DateTime.UtcNow;
_context.ProductionUploads.Add(数据);
_SaveChanges();
data.RegistryNumber=“P”+data.Id.ToString().PadLeft(6,'0');
_SaveChanges();
recaptcha=data.recaptcha;
}
捕获(例外情况除外)
{
发送例外邮件(ex);
_logger.LogError(“{0}\n{1}”,例如Message,例如StackTrace);
投掷;
}
返回TCHA;
}
[HttpPost]
[DisableRequestSizeLimit]
[路由(“上传”)]
公共无效上载文档()
{
List fileData=新列表();
尝试
{
var recaptcha=Request.Form[“data”].ToString();
var files=Request.Form.files;
//验证文档
如果(files.Count>0)
{
uint maximumDocumentSize=_configuration.GetSection(“AppSettings”).GetValue(“maximumDocumentSize”);
List allowedDocumentTypes=_configuration.GetSection(“AppSettings:allowedDocumentTypes”).Get();
var fileExt=Path.GetExtension(文件[0].FileName);
如果(文件[0]。长度==0 | |文件[0]。长度>最大文档大小||
(!allowedDocumentTypes.Any(ft=>ft.Extension.ToLower()==fileExt.ToLower()&&(string.IsNullOrEmpty(ft.ContentType)| | ft.ContentType.ToLower()==files[0].ContentType.ToLower()))
{
抛出新异常(string.Format(“服务器端文件验证失败:{0},{1}字节,{2}内容类型”,文件[0]。文件名,文件[0]。长度,文件[0]。内容类型));
}
}
“验证求职信
如果(files.Count>1)
{
uint maximumCoverLetterSize=_配置.GetSection(“应用设置”).GetValue(“maximumCoverLetterSize”);
列出allowedCoverLetterTypes=_configuration.GetSection(“AppSettings:allowedCoverLetterTypes”).Get();
var fileExt=Path.GetExtension(文件[1].FileName);
如果(文件[1]。长度==0 | |文件[1]。长度>maximumCoverLetterSize||
(!allowedCoverLetterTypes.Any(ft=>ft.Extension.ToLower()==fileExt.ToLower()&&(string.IsNullOrEmpty(ft.ContentType)| | ft.ContentType.ToLower()==files[1].ContentType.ToLower()))
{
抛出新异常(string.Format(“服务器端文件验证失败:{0},{1}字节,{2}内容类型”,文件[1]。文件名,文件[1]。长度,文件[1]。内容类型));
}
}
'从数据库获取以前保存的提交'
ProductionUpload ProductionUpload=\u context.ProductionUploads.SingleOrDefault(sr=>sr.Recaptcha==Recaptcha);
if(productionUpload==null | | productionUpload.Id==0)
{
抛出新异常(“无效的Recaptcha响应:“+Recaptcha”);
}
'保存上载的文件'
字符串fileUploadPath=_configuration.GetSection(“AppSettings”).GetValue(“fileUploadPath”);
字符串pathToSave=Path.Combine(fileUploadPath,Guid.NewGuid().ToString());
如果(!Directory.Exists(pathToSave))
CreateDirectory(路径保存);
对于(int i=0;i