部署依赖appsettings.json的ASP.NET Core MVC网站遇问题求助
部署使用appsettings.json的ASP.NET Core网站指南
关于Web.config的疑问
你的项目里没有Web.config是正常的——ASP.NET Core SDK风格项目不需要手动创建这个文件,当你发布项目到IIS环境时,发布工具会自动生成Web.config,用来配置IIS的ASP.NET Core模块,你不需要手动修改它。
部署步骤
1. 生成发布包
- Visual Studio操作:右键项目 → 选择「发布」,选择发布目标(比如本地文件夹、IIS等),按向导完成发布。
- 命令行操作:在项目根目录执行
dotnet publish -c Release,发布产物会生成在bin/Release/net[你的.NET版本]/publish文件夹下。 - 关键设置:确保
appsettings.json的「复制到输出目录」属性设为「如果较新则复制」或「始终复制」(右键文件→属性可设置),否则发布包中会缺少这个配置文件。
2. 配置生产环境连接字符串
有两种可靠的方式修改生产环境的连接字符串:
- 直接修改发布包中的appsettings.json:打开publish文件夹里的appsettings.json,把
ConnectionStrings下的db2T值替换为主机提供的生产连接字符串(注意生产环境通常用SQL Server认证,格式类似Server=xxx;Database=xxx;User Id=xxx;Password=xxx;MultipleActiveResultSets=true;TrustServerCertificate=true;)。 - 用环境变量覆盖(更安全):在主机的IIS站点中,打开「配置编辑器」,选择
system.webServer/aspNetCore节点,在environmentVariables里添加一条记录:键为ConnectionStrings__db2T(双下划线对应配置文件里的层级),值为主机提供的连接字符串。这种方式不需要修改配置文件,还能避免敏感信息暴露。
3. 部署到主机
- 在主机IIS中创建新站点,将物理路径指向发布包所在的文件夹。
- 确认主机已安装与你项目.NET版本一致的ASP.NET Core Runtime(如果没装,需要先安装)。
- 启动站点,测试是否正常访问。
排查连接字符串不生效的问题
- 先检查发布包中的appsettings.json,确认连接字符串已经正确替换。
- 验证主机的SQL Server允许外部连接,连接字符串中的服务器地址、账号密码(如果用SQL认证)无误。
- 临时添加日志排查:在Startup.cs的
ConfigureServices方法中加入一行Console.WriteLine($"当前连接字符串: {stringConnectdb}");,然后查看主机的ASP.NET Core日志,确认程序读取到的连接字符串是否正确(生产环境记得移除这行,避免泄露敏感信息)。 - 检查
DbMarketsContext是否存在硬编码的连接字符串,确保它确实是从配置中读取的。
你提供的代码参考
Program.cs
using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); var startup = new Startup(builder.Configuration); // My custom startup class. startup.ConfigureServices(builder.Services); // Add services to the container. var app = builder.Build(); startup.Configure(app, app.Environment); // Configure the HTTP request pipeline. app.Run();
appsettings.json
{ "ConnectionStrings": { "db2T": "Server=DESKTOP-9NQ1AQE\\QUANGTRUONG;Database=dbMarkets;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=true;" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
Startup.cs
using AspNetCoreHero.ToastNotification; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.EntityFrameworkCore; using System.Text.Encodings.Web; using System.Text.Unicode; using Web2T.Models; public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { this.Configuration = configuration; } // This method gets called by the runtime. Use this method to add serices to the container. public void ConfigureServices(IServiceCollection services) { var stringConnectdb = Configuration.GetConnectionString("db2T"); services.AddDbContext<DbMarketsContext>(option => option.UseSqlServer(stringConnectdb)); services.AddSingleton<HtmlEncoder>(HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.All })); services.AddSession(); services.AddHttpClient(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(p => { p.LoginPath = "/dang-nhap.html"; p.AccessDeniedPath = "/"; }); services.AddControllersWithViews().AddRazorRuntimeCompilation(); services.AddNotyf(config => { config.DurationInSeconds = 3; config.IsDismissable = true; config.Position = NotyfPosition.BottomRight; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(WebApplication app, IWebHostEnvironment env) { if (!env.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSession(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "areas", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }
内容的提问来源于stack exchange,提问作者Quang Trường Phạm
相关产品推荐
相关产品推荐

