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

在Digital Ocean发布ASP.NET Core Web API后出现500内部服务器错误

问题描述
  • 在DigitalOcean的Ubuntu 22.04 Droplet中,通过Nginx托管使用SQLite的ASP.NET Core Web API
  • 本地执行dotnet build && dotnet run时,Swagger可正常打开,且能从数据库获取数据
  • 执行dotnet publish发布后,在/etc/systemd/system中创建服务并通过sudo systemctl start myapi.service启动,Swagger能成功打开,但所有HTTP请求均返回Error 500: Internal Service Error
  • 服务配置文件如下:
[Unit]
Description=My API

[Service]
WorkingDirectory=/home/myAPI/bin/Debug/net6.0/publish
ExecStart=/usr/bin/dotnet /home/myAPI/bin/Debug/net6.0/publish/myAPI.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target
排查与解决步骤

1. 检查SQLite数据库文件权限

服务运行用户是www-data,必须确保该用户对SQLite数据库文件及所在目录拥有读写权限:

# 替换为你的数据库文件所在目录路径
sudo chown -R www-data:www-data /path/to/your/sqlite/database/folder
sudo chmod -R 755 /path/to/your/sqlite/database/folder

例如,如果数据库文件在发布目录的Data子文件夹中,路径应为/home/myAPI/bin/Debug/net6.0/publish/Data

2. 查看应用日志定位具体错误

通过systemd日志查看应用运行时的错误详情:

sudo journalctl -u myapi.service -f

日志会明确显示500错误的根源,比如数据库文件无法访问、连接字符串配置错误等。

也可以在appsettings.Production.json中配置更详细的日志输出,帮助排查:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore": "Debug"
    }
  }
}

3. 确认生产环境的连接字符串

服务设置了ASPNETCORE_ENVIRONMENT=Production,检查appsettings.Production.json中的连接字符串是否正确指向发布后的数据库文件:

"ConnectionStrings": {
  "DefaultConnection": "Data Source=./Data/MyDatabase.db"
}

注意相对路径是基于服务的WorkingDirectory(即/home/myAPI/bin/Debug/net6.0/publish)

4. 检查发布目录权限

确保www-data用户对整个发布目录有访问权限:

sudo chown -R www-data:www-data /home/myAPI/bin/Debug/net6.0/publish

5. 验证服务运行状态

重启服务并检查是否正常运行:

sudo systemctl restart myapi.service
sudo systemctl status myapi.service

确认服务处于active (running)状态,无启动失败提示。

内容的提问来源于stack exchange,提问作者Azamat Salamat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:31:13