ASP.NET Core 简介
ASP.NET Core 是微软开发的新一代跨平台、开源的 Web 框架,用于构建现代化的云原生应用程序。以下是 ASP.NET Core 的全面介绍。
一、核心特性
-
跨平台支持
- 支持 Windows、Linux 和 macOS
- 可部署到 Docker 容器
- 支持云原生架构
-
高性能
- 基于 Kestrel 高性能 Web 服务器
- 异步编程模型
- 最小化开销的中间件管道
-
统一框架
- 统一 MVC 和 Web API 开发
- 支持 Razor Pages 和传统 MVC
- 内置依赖注入
-
模块化设计
- 中间件管道架构
- 可扩展的配置系统
- 轻量级核心
-
现代化开发体验
- 支持 C# 8.0+ 特性
- 集成 Razor 视图引擎
- 前后端分离支持
二、主要组件
1. Kestrel 服务器
- 高性能跨平台 Web 服务器
- 作为 ASP.NET Core 的默认开发服务器
- 支持 HTTPS 和 HTTP/2
2. 中间件管道
- 请求处理流水线
- 可扩展的中间件组件
- 常见中间件:路由、静态文件、身份验证等
3. 路由系统
- 灵活的 URL 路由
- 支持属性路由和传统路由
- 路由约束和数据令牌
4. 依赖注入
- 内置 IoC 容器
- 支持构造函数注入
- 生命周期管理(Transient/Scoped/Singleton)
5. 配置系统
- 多源配置支持(appsettings.json、环境变量等)
- 强类型配置
- 配置热更新
三、应用模型
1. MVC (Model-View-Controller)
- 传统的基于控制器的 Web 应用
- 支持 RESTful API 开发
- 视图引擎(Razor)支持
2. Razor Pages
- 更简单的页面为中心的开发模型
- 类似于传统 Web Forms 的开发体验
- 适合内容型网站
3. Blazor
- 基于 WebAssembly 的 .NET 前端框架
- 支持交互式 Web UI 开发
- 可选择服务器端或客户端渲染
四、开发体验
1. 开发工具
- Visual Studio 集成开发环境
- Visual Studio Code 支持
- .NET CLI 命令行工具
2. 热重载
- 代码更改后自动应用
- 不需要重新启动应用
- 提高开发效率
3. 调试支持
- 内置调试器
- 性能分析工具
- 日志记录系统
五、部署选项
1. 自托管
- 直接运行可执行文件
- 适合小型应用
2. IIS 托管
- 通过 ASP.NET Core 模块
- 支持 Windows Server
3. Docker 容器
- 官方 .NET 镜像
- 微服务架构友好
- Kubernetes 集成
4. 云平台
- Azure App Service
- AWS Elastic Beanstalk
- Google Cloud Run
六、性能优化
-
异步编程
- 使用 async/await 模式
- 避免阻塞调用
-
静态文件处理
- 启用响应缓存
- 配置静态文件中间件
-
连接池
- 数据库连接池
- HTTP 客户端工厂
-
压缩
- 启用响应压缩
- 支持 Brotli 和 Gzip
-
最小化中间件
- 只包含必要的中间件
- 优化中间件顺序
七、安全性
-
身份验证
- Cookie 认证
- JWT Bearer 认证
- OAuth/OpenID Connect
-
授权
- 基于角色的授权
- 基于策略的授权
- 资源级授权
-
数据保护
- 加密敏感数据
- 安全存储密钥
- 防止数据篡改
-
CORS
- 配置跨域资源共享
- 限制允许的来源
-
防注入
- 参数化查询
- 输入验证
- 输出编码
八、与旧版 ASP.NET 的区别
特性 | ASP.NET Core | 传统 ASP.NET |
---|---|---|
平台 | 跨平台 | Windows 专用 |
性能 | 更高 | 较低 |
架构 | 中间件管道 | 管道事件模型 |
配置 | 灵活的多源配置 | 主要基于 web.config |
托管 | Kestrel/IIS | IIS |
开发模式 | 现代化(如 Razor Pages) | Web Forms/MVC |
性能分析 | 内置工具 | 第三方工具 |
九、学习资源
-
官方文档
- ASP.NET Core 官方文档
-
教程
- Microsoft Learn 平台
- Pluralsight 课程
- Udemy 课程
-
社区资源
- Stack Overflow
- GitHub 上的开源项目
- .NET 用户组
十、适用场景
-
Web API 开发
- RESTful 服务
- 微服务架构
- 前后端分离应用
-
企业级 Web 应用
- 内容管理系统
- 电子商务平台
- 客户关系管理
-
实时应用
- 信号R 实时通信
- WebSocket 应用
-
移动后端
- 移动应用 API
- 跨平台移动后端
十一 项目示例并简化swagger集成
使用VS2022创建项目
如果没有安装VS2022,需要提前安装后才能就行此步骤,并且选择集成 ASP .NET Core负载。
创建完成后的项目结构:
其中的Extensions文件夹需要手动创建,然后在Extensions中创建类SwaggerExtension.cs,
SwaggerExtension.cs
namespace WebApi.Extensions;
using System.Reflection;
using APIVersion;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
/// <summary>
/// Swagger扩展类
/// </summary>
public static class SwaggerExtension
{
/// <summary>
/// 添加Swagger扩展
/// </summary>
/// <param name="Service"></param>
public static void AddSwaggerExtension(this IServiceCollection Service)
{
Service.AddEndpointsApiExplorer();
Service.AddSwaggerGen(option =>
{
#region 注释展示
{
// 获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
//string basePath = AppContext.BaseDirectory;
//string xmlPath = Path.Combine(basePath, "netCoreWebApi.xml");
//option.IncludeXmlComments(xmlPath);
// 启用 XML 注释(需在项目属性中生成 XML 文档文件)
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
option.IncludeXmlComments(xmlPath);
}
#endregion
#region 支持Swagger版本控制
{
foreach (FieldInfo filed in typeof(ApiVersionInfo).GetFields())
{
//option.SwaggerDoc(filed.Name, new OpenApiInfo()
//{
// Title = $"netCoreWebApi API {filed.Name}",
// Version = filed.Name,
// Description = $"netCoreWebApi API {filed.Name} 版本"
//});
option.SwaggerDoc($"{filed.Name}", new OpenApiInfo
{
Version = $"{filed.Name}",
Title = $"工业生产中控服务器系统- {filed.Name}",
Description = $"工业生产中控服务器系统{filed.Name} 版本",
Contact = new OpenApiContact
{
Name = "wsb",
Email = "88899@qq.com"
},
License = new OpenApiLicense
{
Name = "许可证",
Url = new Uri("https://blog.youkuaiyun.com/XiaoWang_csdn?spm=1000.2115.3001.5343")
}
});
}
}
#endregion
#region 支持token传值
{
option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"", // 描述
Name = "Authorization", // 授权名称
In = ParameterLocation.Header, // 授权位置,放在头信息进行传值
Type = SecuritySchemeType.ApiKey, // 授权类型
BearerFormat = "JWT", // 格式是JWT
Scheme = "Bearer"
});
// 添加安全要求
option.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference()
{
Id = "Bearer", // 必须和上面一致
Type = ReferenceType.SecurityScheme
}
},
new string[] { }
}
});
}
#endregion
});
}
/// <summary>
/// 使能Swagger扩展
/// </summary>
/// <param name="app"></param>
public static void UseSwaggerExtension(this WebApplication app)
{
app.UseSwagger();
app.UseSwaggerUI(option =>
{
foreach (FieldInfo filed in typeof(ApiVersionInfo).GetFields())
{
option.SwaggerEndpoint($"/swagger/{filed.Name}/swagger.json", filed.Name);
}
});
}
}
改造Program.cs类,如下:
Program.cs
using Microsoft.Extensions.Configuration;
using Microsoft.OpenApi.Models;
using NLog.Web;
using System.Configuration;
using System.Reflection;
using WebApi.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerExtension();
builder.Logging.AddNLog("");
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwaggerExtension();
}
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.UseStaticFiles();
app.Run();
创建版本管理类库APIVersion,该类库适用于当前工程下的所有项目,
在APIVersion工程下创建类ApiVersionInfo.cs:
ApiVersionInfo.cs
namespace APIVersion;
public class ApiVersionInfo
{
public static string V1;
public static string V2;
public static string V3;
public static string V4;
public static string V5;
public static string V6;
public static string V7;
public static string V8;
public static string V9;
public static string V10;
public static string V11;
public static string V12;
}
生成APIVersion工程,
在WebApi项目中引用APIVersion项目
此时,项目可以正常运行了,来看看效果:
源码下载地址: