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

ASP.NET Core 7中如何将指定示例的Startup.cs合并至Program.cs

将ASP.NET Core示例的Startup.cs合并到ASP.NET Core 7的Program.cs

核心逻辑说明

ASP.NET Core 6及以后版本移除了Startup.cs,把原Startup.ConfigureServices(服务注册)和Startup.Configure(请求管道配置)的代码直接整合到Program.cs的主机构建流程中,功能完全兼容,只是代码结构更简洁。

具体合并步骤(对应目标示例项目)

示例项目的Startup.cs核心是身份验证配置、Graph API集成和请求管道设置,按以下步骤完成迁移:

1. 替换Program.cs默认代码

删除Program.cs原有内容,粘贴以下整合后的代码:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);

// 原Startup.ConfigureServices中的服务注册逻辑
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "User.Read" })
    .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
    .AddInMemoryTokenCaches();

builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddRazorPages();

var app = builder.Build();

// 原Startup.Configure中的请求管道配置逻辑
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

// 中间件顺序不可调换:先认证,再授权
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.MapControllers();

app.Run();

2. 配置appsettings.json

确保项目的appsettings.json包含示例所需的配置节点,格式参考:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[你的租户域名,例如contoso.onmicrosoft.com]",
    "TenantId": "[租户ID或common/organizations]",
    "ClientId": "[应用注册的客户端ID]",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath ": "/signout-callback-oidc"
  },
  "DownstreamApi": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "User.Read"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

3. 关键验证点

  • 原Startup.ConfigureServices中的服务注册代码,直接放到builder.Services调用链下即可
  • 中间件顺序必须严格遵循:UseHttpsRedirection→UseStaticFiles→UseRouting→UseAuthentication→UseAuthorization→路由映射
  • 确保安装了所需NuGet包:Microsoft.Identity.Web、Microsoft.Identity.Web.UI、Microsoft.Identity.Web.MicrosoftGraph

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:43:16