亲爱的,我正在使用asp.net核心3.1的问题,当我下载它给我这个错误(无法返回空从一个操作方法与返回类型'Microsoft.AspNetCore.Mvc.IActionResult)
这个模型
{
public class Files
{
[Key]
public int DocumentId { get; set; }
public string Name { get; set; }
public string FileType { get; set; }
public byte[] DataFiles { get; set; }
}
}
这个控制器
namespace Info.Controllers
{
public class DemoController : Controller
{
private readonly ApplicationDbContext _context;
public DemoController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var result = _context.Files.ToList();
return View(result);
}
[HttpPost]
public IActionResult Index(IFormFile files)
{
if (files != null)
{
if (files.Length > 0)
{
//Getting FileName
var fileName = Path.GetFileName(files.FileName);
//Getting file Extension
var fileExtension = Path.GetExtension(fileName);
// concatenating FileName + FileExtension
var newFileName = String.Concat(Convert.ToString(Guid.NewGuid()), fileExtension);
var objfiles = new Files()
{
DocumentId = 0,
Name = newFileName,
FileType = fileExtension,
};
using (var target = new MemoryStream())
{
files.CopyTo(target);
objfiles.DataFiles = target.ToArray();
}
_context.Files.Add(objfiles);
_context.SaveChanges();
}
}
return RedirectToAction("Index");
}
// public IActionResult DownloadImage(int id)
// {
// byte[] bytes;
// string fileName, contentType;
// var item = _context.Files.FirstOrDefault(c => c.DocumentId == id);
// if (item != null)
// {
// fileName = item.Name;
// contentType = item.FileType;
// bytes = item.DataFiles;
// return File(bytes, contentType, fileName);
// }
// return View();
// }
public async Task<IActionResult> DownloadImage(int id)
{
var file = await _context.Files.Where(x => x.DocumentId == id).FirstOrDefaultAsync();
if (file == null) return null;
return File(file.DataFiles, file.Name + file.FileType);
}
}
}
2条答案
按热度按时间6tdlim6h1#
这个代码对我有用
}
flvlnr442#
尝试在OkObjectResul中返回空值。