You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web API文件上传:文件存路径成功但数据库未保存路径

问题描述

我有一个ASP.NET Core Web API,尝试将文件上传至指定路径Upload\Files,同时将文件路径存储到数据库中。使用Swagger测试时,文件可成功保存到目标文件夹,但文件路径并未写入数据库,且未收到任何错误提示。


相关代码文件

Program.cs

using FileUploadContenet.Data;
using Microsoft.EntityFrameworkCore;
using System.Globalization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Configuration.AddJsonFile("appsettings.json");

builder.Services.AddDbContext<ApplicationDbContext>(Options =>
{
    Options.UseSqlServer(builder.Configuration.GetConnectionString("SQLServerConnection"));
});

CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "SQLServerConnection": "Server=ServerName;Database=DatabaseName;Integrated Security=True; Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true;"
  },
  "AllowedHosts": "*"
}

数据表定义

CREATE TABLE [dbo].[UploadContent] 
(
    [Id]         INT IDENTITY (1, 1) NOT NULL,
    [fileUpload] VARCHAR (MAX) NULL,

    CONSTRAINT [PK_UploadContent] PRIMARY KEY CLUSTERED ([Id] ASC)
);

模型类

public class UploadContent
{
    [Key]
    public int Id { get; set; }
    public string fileUpload { get; set; }
}

ApplicationDbContext文件

using FileUploadContenet.Model;
using Microsoft.EntityFrameworkCore;

namespace FileUploadContenet.Data
{
    public class ApplicationDbContext : DbContext
    {
        public DbSet<UploadContent> UploadContent { get; set; }
        private readonly IConfiguration _configuration;

        public ApplicationDbContext(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IConfiguration configuration) : base(options)
        {
            _configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(_configuration.GetConnectionString("SQLServerConnection"));
        }
    }
}

API控制器代码

using FileUploadContenet.Data;
using FileUploadContenet.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Globalization;

namespace FileUploadContenet.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public FilesController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpPost]
        [Route("UploadFile")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> UploadFile(IFormFile file, CancellationToken cancellationToken)
        {
            var result = await WriteFile(file);
            return Ok(result);
        }

        private async Task<string> WriteFile(IFormFile file)
        {
            string filename = "";

            try
            {
                var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                filename = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture) + extension;

                var directoryPath = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\Files");

                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                var filePath = Path.Combine(directoryPath, filename);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // Save the file path to the database
                SaveFilePathToDatabase(filePath);
            }
            catch (Exception ex)
            {
                // Handle exceptions (log or return an error)
            }

            return filename;
        }

        private void SaveFilePathToDatabase(string filePath)
        {
            try
            {
                var uploadContent = new UploadContent
                {
                    fileUpload = filePath
                };

                _context.UploadContent.Add(uploadContent);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine("File not stored into the database");
            }
        }
    }
}

问题排查与修复方案

1. 简化DbContext配置(核心修复)

原ApplicationDbContext存在冗余配置,导致EF Core上下文实例不一致,是路径无法写入数据库的主要原因。修改后的ApplicationDbContext:

using FileUploadContenet.Model;
using Microsoft.EntityFrameworkCore;

namespace FileUploadContenet.Data
{
    public class ApplicationDbContext : DbContext
    {
        public DbSet<UploadContent> UploadContent { get; set; }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }
    }
}

2. 修复异步流程与异常处理

原代码同步调用数据库操作且吞掉异常,导致无法排查错误。修改控制器方法为全异步,并暴露异常信息:

[HttpPost]
[Route("UploadFile")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UploadFile(IFormFile file, CancellationToken cancellationToken)
{
    if (file == null || file.Length == 0)
    {
        return BadRequest("未上传有效文件");
    }

    try
    {
        var result = await WriteFile(file);
        return Ok(result);
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, $"上传失败: {ex.Message}");
    }
}

private async Task<string> WriteFile(IFormFile file)
{
    var extension = Path.GetExtension(file.FileName);
    var filename = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture) + extension;
    var directoryPath = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\Files");

    if (!Directory.Exists(directoryPath))
    {
        Directory.CreateDirectory(directoryPath);
    }

    var filePath = Path.Combine(directoryPath, filename);

    using (var stream = new FileStream(filePath, FileMode.Create))
    {
        await file.CopyToAsync(stream);
    }

    await SaveFilePathToDatabaseAsync(filePath);
    return filename;
}

private async Task SaveFilePathToDatabaseAsync(string filePath)
{
    var uploadContent = new UploadContent
    {
        fileUpload = filePath
    };

    _context.UploadContent.Add(uploadContent);
    await _context.SaveChangesAsync();
}

3. 验证数据库连接

确保appsettings.json中的SQLServerConnection连接字符串正确,服务器名、数据库名无误,且应用程序拥有数据库读写权限。


内容的提问来源于stack exchange,提问作者Sa J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:58:11