Как указал @VDWWD, вы не должны хранить файлы в объекте Session - вместо этого храните их на диске. Ниже вы можете найти быструю реализацию этой функции.
public interface IFileStorage
{
Task UploadFile(string fileName, Stream fileContent);
void TryRemoveFile(string fileName, out bool fileRemoved);
void GetFile(string fileName);
}
public class FileSystemStorage : IFileStorage
{
private readonly PhysicalFileProvider _fileProvider;
private readonly ILogger<FileSystemStorage>_logger;
public FileSystemStorage(IFileProvider fileProvider, ILogger<FileSystemStorage> logger)
{
_fileProvider = (PhysicalFileProvider)fileProvider;
_logger = logger;
}
public void GetFile(string fileName)
{
throw new NotImplementedException();
}
public void TryRemoveFile(string fileName, out bool fileRemoved)
{
try
{
RemoveFile(fileName);
fileRemoved = true;
}
catch(Exception ex)
{
_logger.LogError($"Couldnt remove file {fileName}: {ex.ToString()}" );
fileRemoved = false;
}
}
public async Task UploadFile(string fileName, Stream fileContent)
{
var filePath = Path.Combine(_fileProvider.Root, fileName);
if (_fileProvider.GetFileInfo(filePath).Exists)
throw new ArgumentException("Given file already exists!");
_logger.LogInformation($"Saving file to: {filePath}..");
using (Stream file = File.Create(filePath))
{
await fileContent.CopyToAsync(file);
file.Flush();
}
_logger.LogInformation($"File: {filePath} saved successfully.");
}
}
В Startup.cs метод ConfigureServices добавьте следующие строки для внедрения FileSystemStorage:
IFileProvider physicalProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "AppData"));
services.AddSingleton<IFileProvider>(physicalProvider);
services.AddTransient<IFileStorage, FileSystemStorage>();
Затем в конструкторе вашего контроллера получите FileSystemStorage пример.