1. ASP.NET Core 面试题概述
ASP.NET Core 是微软推出的跨平台、高性能开源Web框架,已成为.NET开发者必须掌握的核心技术。在面试中,ASP.NET Core相关问题的考察频率越来越高,主要聚焦于框架特性、中间件、依赖注入、配置系统等核心概念。
作为面试官,我通常会从以下几个维度考察候选人的ASP.NET Core掌握程度:
- 框架基础架构理解
- 核心功能模块的实战应用
- 性能优化与安全实践
- 与其他技术的集成能力
2. 核心面试题解析
2.1 框架基础
ASP.NET Core与ASP.NET的区别
- 跨平台支持(Windows/Linux/macOS)
- 高性能的Kestrel Web服务器
- 内置依赖注入容器
- 模块化的中间件管道
- 统一的项目配置系统
Startup类的作用
public class Startup { public void ConfigureServices(IServiceCollection services) { // 依赖注入配置 } public void Configure(IApplicationBuilder app) { // 中间件管道配置 } }
2.2 中间件
中间件执行顺序的重要性
- 异常处理中间件应放在管道最前面
- 静态文件中间件通常在授权中间件之前
- 终结点路由中间件应放在管道末尾
自定义中间件示例
public class RequestLoggerMiddleware { private readonly RequestDelegate _next; public RequestLoggerMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { // 请求前处理 LogRequest(context); await _next(context); // 请求后处理 LogResponse(context); } }
2.3 依赖注入
服务生命周期比较
生命周期 说明 适用场景 Singleton 整个应用生命周期 配置服务、日志服务 Scoped 每次请求 DbContext、仓储 Transient 每次请求 轻量级无状态服务 服务注册最佳实践
services.AddScoped<IUserRepository, UserRepository>(); services.AddSingleton<ICacheService, RedisCacheService>();
3. 高级特性与优化
3.1 配置系统
多配置源支持
new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .AddCommandLine(args) .Build();选项模式
services.Configure<DatabaseOptions>(Configuration.GetSection("Database"));
3.2 性能优化
响应缓存
[ResponseCache(Duration = 60)] public IActionResult Get() { return View(); }异步编程
public async Task<IActionResult> GetUsers() { var users = await _userService.GetAllAsync(); return Ok(users); }
4. 安全实践
4.1 认证与授权
JWT认证配置
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; });基于策略的授权
services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin")); });
5. 实战问题与解决方案
5.1 常见问题排查
跨域问题
services.AddCors(options => { options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); });静态文件访问
app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")), RequestPath = "/static" });
5.2 测试相关
单元测试示例
[Fact] public void Calculate_ShouldReturnCorrectResult() { // Arrange var calculator = new Calculator(); // Act var result = calculator.Add(2, 3); // Assert Assert.Equal(5, result); }集成测试配置
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class { protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { // 替换测试需要的服务 }); } }
6. 架构设计考量
6.1 分层架构
典型项目结构
MyProject/ ├── Controllers/ ├── Services/ ├── Repositories/ ├── Models/ ├── DTOs/ └── Infrastructure/领域驱动设计应用
public class Order : IAggregateRoot { private readonly List<OrderItem> _items = new(); public IReadOnlyCollection<OrderItem> Items => _items.AsReadOnly(); public void AddItem(Product product, int quantity) { // 业务规则验证 _items.Add(new OrderItem(product, quantity)); } }
6.2 微服务集成
gRPC服务定义
service ProductService { rpc GetProduct (ProductRequest) returns (ProductResponse); } message ProductRequest { int32 id = 1; } message ProductResponse { int32 id = 1; string name = 2; double price = 3; }健康检查配置
services.AddHealthChecks() .AddSqlServer(Configuration.GetConnectionString("Default")) .AddRedis(Configuration.GetConnectionString("Redis"));
7. 部署与监控
7.1 部署选项
Docker部署
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base WORKDIR /app EXPOSE 80 FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build WORKDIR /src COPY ["MyProject.csproj", "."] RUN dotnet restore "MyProject.csproj" COPY . . RUN dotnet build "MyProject.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "MyProject.dll"]Kubernetes部署
apiVersion: apps/v1 kind: Deployment metadata: name: myproject spec: replicas: 3 selector: matchLabels: app: myproject template: metadata: labels: app: myproject spec: containers: - name: myproject image: myregistry/myproject:latest ports: - containerPort: 80
7.2 监控与日志
Serilog配置
Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day) .CreateLogger();Application Insights集成
services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);
8. 最新特性与趋势
8.1 .NET 6/7新特性
最小API
var app = WebApplication.Create(args); app.MapGet("/", () => "Hello World!"); app.Run();热重载
dotnet watch run
8.2 性能优化技巧
响应压缩
services.AddResponseCompression(options => { options.Providers.Add<GzipCompressionProvider>(); options.EnableForHttps = true; });对象池
var pool = new DefaultObjectPool<MyObject>(new MyObjectPooledPolicy()); var obj = pool.Get(); try { // 使用对象 } finally { pool.Return(obj); }
9. 面试准备建议
技术深度与广度
- 深入理解至少3个核心模块(如中间件、DI、路由)
- 了解常见性能优化手段
- 掌握基本的安全防护措施
项目经验准备
- 准备2-3个能体现技术深度的项目案例
- 能够清晰描述架构设计决策
- 准备好对项目中技术难点的复盘
编码测试准备
- 熟悉常见算法题
- 练习在有限时间内完成小型功能实现
- 准备解释代码设计思路的能力
在实际面试中,我通常会根据候选人的简历和岗位要求,从这些题目中选择合适的进行提问。建议候选人不仅要记住答案,更要理解背后的原理和设计思想。