简体   繁体   English

ASP.NET Core 2.0无法返回EF触摸对象

[英]ASP.NET Core 2.0 fails to return EF touched object

I have the following post function, which basically just takes a multipart post (fileDataModel.File is a IFormFile object) and saves the file metadata to a database and the file to hard drive. 我具有以下发布功能,基本上只需要进行多部分发布(fileDataModel.File是IFormFile对象),并将文件元数据保存到数据库中,并将文件保存到硬盘中。

    [HttpPost("filedata")]
    public async Task<IActionResult> PostFileData([FromForm] FileDataBindingModel fileDataModel)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }           

        var contactData = await _context.ContactData.FirstOrDefaultAsync(e => e.Id == fileDataModel.ContactId);
        if (contactData == null)
        {
            ModelState.AddModelError("ContactId", "No such contact exists.");
            return BadRequest(ModelState);
        }

        FileData fileData = new FileData
        {
            ContactId = fileDataModel.ContactId,
            Contact = contactData
        };

        var fileName = fileDataModel.File.FileName;

        var FileStorageDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "filestorage");
        Directory.CreateDirectory(FileStorageDir);
        var FileStoragePath = FileStorageDir + "\\" + DateTimeOffset.UtcNow.ToUnixTimeSeconds() + fileName;
        using (FileStream fStream = new FileStream(FileStoragePath, FileMode.OpenOrCreate)) {
            await fileDataModel.File.CopyToAsync(fStream);
        }
        fileData.FilePath = FileStoragePath;
        fileData.OriginalFileName = fileName;
        fileData.Id = Guid.NewGuid();

        _context.FileData.Add(fileData);
        await _context.SaveChangesAsync();

        return Ok(fileData);
    }        

Now this function works fine, does what it should, but fails to return if the return object in the Ok() has been touched by EF at some point (so specifically, fileData and contactData). 现在,此函数可以正常工作,执行应有的操作,但是如果EF在某些时候(特别是fileData和contactData)已触摸Ok()中的返回对象,则无法返回。 Postman reports no response received. 邮递员报告未收到回复。 If I input any other object, it returns the object just fine. 如果我输入任何其他对象,它将返回该对象。 I can't seem to find the hitch, as I get no exception or anything, just a failure to return. 我似乎找不到障碍,因为我没有例外或其他任何东西,只是失败了。 Any help would be greatly appreciated. 任何帮助将不胜感激。

也许尝试使用非异步版本对其进行测试,以查看其是否返回错误?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM