.NET Core 中推荐使用的10大优秀库,你用到过几个?
yuyutoo 2025-01-14 18:42 4 浏览 0 评论
概述:Microsoft 的 .NET Core 生态系统中的中间件已经发生了重大变化,包括无缝集成到应用程序管道中的内置和第三方组件,协调客户端和服务器之间的数据流。它通过身份验证、日志记录和路由等功能增强了应用程序功能,确保了可扩展性和可维护性我将展示 Microsoft 的十种出色的中间件解决方案。无论你是经验丰富的开发人员还是 .NET Core 新手,此探索都提供了宝贵的见解和资源来增强你的开发项目。AutoMapper它是软件开发中的一个库,可简化不同对象类型之间的数据传输。开发人员无需手动复制每个属性,而是通过简单的配置过程定义映射。这种自动化可以节省时间,减少错误,并增强代码的可读性
Microsoft 的 .NET Core 生态系统中的中间件已经发生了重大变化,包括无缝集成到应用程序管道中的内置和第三方组件,协调客户端和服务器之间的数据流。它通过身份验证、日志记录和路由等功能增强了应用程序功能,确保了可扩展性和可维护性
我将展示 Microsoft 的十种出色的中间件解决方案。无论你是经验丰富的开发人员还是 .NET Core 新手,此探索都提供了宝贵的见解和资源来增强你的开发项目。
- AutoMapper
它是软件开发中的一个库,可简化不同对象类型之间的数据传输。开发人员无需手动复制每个属性,而是通过简单的配置过程定义映射。这种自动化可以节省时间,减少错误,并增强代码的可读性和可维护性。通过消除手动任务,AutoMapper 使开发人员能够专注于应用程序逻辑,使其成为各种规模项目的宝贵工具。最终,它简化了对象映射,促进了高效且易于管理的软件开发。
通常在应用程序初始化阶段设置映射。
public class SourceClass
{
public int Id { get; set; }
public string Name { get; set; }
// Other properties
}
public class DestinationClass
{
public int Id { get; set; }
public string Name { get; set; }
// Other properties
}
将 AutoMapper 配置为将属性从SourceClassDestinationClass.
using AutoMapper;
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<SourceClass, DestinationClass>();
// You can define more mappings here if needed
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Other service configurations
services.AddAutoMapper(typeof(MappingProfile)); // Register MappingProfile
}
}
public class YourService
{
private readonly IMapper _mapper;
public YourService(IMapper mapper)
{
_mapper = mapper;
}
public DestinationClass MapObjects(SourceClass source)
{
// Mapping SourceClass object to DestinationClass object
DestinationClass destination = _mapper.Map<SourceClass, DestinationClass>(source);
return destination;
}
}
2. Swagger
它通过基于 API 端点、模型和元数据自动生成详细文档来简化 Swagger 文档的创建。其主要功能包括:
- 生成 API 端点、HTTP 方法和请求/响应模型的文档。
- 它提供了一个交互式的 Swagger UI,使用户能够直接探索和测试 API 功能。
- 与 ASP.NET Core 应用程序无缝集成,只需最少的配置。
- 提供用于控制 Swagger UI 的外观和行为的自定义选项。
- 允许用户通过在 Swagger UI 中执行请求和检查响应来测试 API 功能。
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Register the Swagger generator
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API V1");
});
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
3. Hangfire
它是一个功能强大的库,用于在 .NET 和 .NET Core 应用程序中执行后台任务。其主要功能包括:
- 允许异步任务执行,而不会阻塞主应用程序线程。
- 使计划任务能够按设定的时间间隔或延迟后运行,从而自动执行重复性进程。
- 提供用户友好的界面来监视和管理后台任务。
- 通过持久存储作业信息来确保任务执行的一致性。
using Hangfire;
using System;
public class MyBackgroundJobService
{
public void ExecuteBackgroundTask()
{
// Example of executing a background task using Hangfire
BackgroundJob.Enqueue(() => SomeBackgroundTaskMethod());
}
public void ScheduleDelayedTask()
{
// Example of scheduling a delayed task using Hangfire
BackgroundJob.Schedule(() => SomeDelayedTaskMethod(), TimeSpan.FromMinutes(30));
}
public void ScheduleRecurringTask()
{
// Example of scheduling a recurring task using Hangfire
RecurringJob.AddOrUpdate(() => SomeRecurringTaskMethod(), Cron.Daily);
}
public void SomeBackgroundTaskMethod()
{
// Logic for executing a background task
Console.WriteLine("Executing background task...");
}
public void SomeDelayedTaskMethod()
{
// Logic for executing a delayed task
Console.WriteLine("Executing delayed task...");
}
public void SomeRecurringTaskMethod()
{
// Logic for executing a recurring task
Console.WriteLine("Executing recurring task...");
}
}
4. Serilog
- 允许将事件记录到各种输出,如文件、数据库和控制台。
- 支持结构化日志记录,使开发人员能够使用丰富的结构化数据记录事件,以提高可读性和分析能力。
- 提供查询功能,实现高效的日志分析,使开发人员能够从记录的事件中提取有意义的见解。
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using System;
public class Program
{
public static void Main(string[] args)
{
// Configure Serilog to log to a file, console, and database
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("log.txt")
.WriteTo.MSSqlServer(connectionString: "YourConnectionString",
tableName: "Logs",
columnOptions: new Serilog.Sinks.MSSqlServer.ColumnOptions(),
restrictedToMinimumLevel: LogEventLevel.Information)
.CreateLogger();
// Log an event with structured data
Log.Information("This is a structured event with {Property1} and {Property2}", "value1", "value2");
// Querying logs
var logs = Log.ReadFrom.MSSqlServer("YourConnectionString", "Logs")
.Query()
.Where(l => l.Level == LogEventLevel.Information && l.MessageTemplate.Text.Contains("structured"))
.OrderByDescending(l => l.Timestamp)
.ToList();
foreach (var log in logs)
{
Console.WriteLine(#34;Timestamp: {log.Timestamp}, Level: {log.Level}, Message: {log.MessageTemplate.Text}");
}
// Dispose the logger
Log.CloseAndFlush();
}
}
5. NancyFx
- 路由 — 提供路由以进行高效的HTTP请求处理。
- 依赖注入 — 支持轻松集成外部组件。
- 模型绑定 — 有助于将 HTTP 请求数据映射到 .NET 对象。
- 可扩展性 — 高度可定制以满足特定要求。
- 轻量级 — 以最小的开销针对性能进行了优化。
using Nancy;
public class SampleModule : NancyModule
{
public SampleModule()
{
// Routing example
Get("/", _ => "Hello, World!"); // Responds to GET requests at the root URL with "Hello, World!"
// Dependency Injection example
var myService = new MyService(); // Instantiate your service
Get("/dependency-injection-example", _ => myService.GetData()); // Inject and use your service
// Model Binding example
Post("/model-binding-example", args =>
{
var requestModel = this.Bind\<MyRequestModel>(); // Bind HTTP request data to MyRequestModel object
return Negotiate.WithModel(requestModel).WithStatusCode(HttpStatusCode.OK); // Respond with bound object
});
// Extensibility: Implement custom route with specific requirements
Get("/custom-route", _ => "Custom route response");
// Lightweight: No extra setup or configuration needed for basic functionality
}
}
public class MyService
{
public string GetData()
{
return "Data from MyService";
}
}
public class MyRequestModel
{
public string Property1 { get; set; }
public int Property2 { get; set; }
}
6. MediatR
它有助于采用命令查询责任分离 (CQRS) 模式,该模式将命令执行(状态更改)与查询处理(数据检索)分开,以提高灵活性和可伸缩性。在 ASP.NET Core 中,MediatR 通过提供用于请求处理的抽象来简化 CQRS 实现。开发人员为命令和查询定义处理程序,使他们能够专注于业务逻辑,而不是复杂的基础结构。
// Define a command to represent a state change
public class CreateProductCommand : IRequest<int>
{
public string Name { get; set; }
public decimal Price { get; set; }
}
// Define a handler for the command
public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand, int>
{
private readonly IDbContext _dbContext;
public CreateProductCommandHandler(IDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<int> Handle(CreateProductCommand request, CancellationToken cancellationToken)
{
var product = new Product
{
Name = request.Name,
Price = request.Price
};
_dbContext.Products.Add(product);
await _dbContext.SaveChangesAsync();
return product.Id;
}
}
// Define a query to represent data retrieval
public class GetProductByIdQuery : IRequest<ProductDto>
{
public int ProductId { get; set; }
}
// Define a handler for the query
public class GetProductByIdQueryHandler : IRequestHandler<GetProductByIdQuery, ProductDto>
{
private readonly IDbContext _dbContext;
public GetProductByIdQueryHandler(IDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<ProductDto> Handle(GetProductByIdQuery request, CancellationToken cancellationToken)
{
var product = await _dbContext.Products.FindAsync(request.ProductId);
return product != null ? new ProductDto { Id = product.Id, Name = product.Name, Price = product.Price } : null;
}
}
// Usage example in controller
public class ProductsController : ControllerBase
{
private readonly IMediator _mediator;
public ProductsController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<ActionResult<int>> CreateProduct(CreateProductCommand command)
{
var productId = await _mediator.Send(command);
return Ok(productId);
}
[HttpGet("{id}")]
public async Task<ActionResult<ProductDto>> GetProduct(int id)
{
var query = new GetProductByIdQuery { ProductId = id };
var product = await _mediator.Send(query);
if (product == null)
return NotFound();
return Ok(product);
}
}
7. FluentValidation
它是一个用于验证模型的 .NET 库,允许开发人员清楚地定义验证规则。它与 ASP.NET Core MVC 无缝集成,支持在 HTTP 请求中自动验证模型。使用 FluentValidation,开发人员可以简化验证,提高代码可读性,并跨应用程序维护干净的验证逻辑。
// Define a model to be validated
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// Create a validator for the model using FluentValidation
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required.");
RuleFor(x => x.Age).InclusiveBetween(18, 100).WithMessage("Age must be between 18 and 100.");
}
}
// In ASP.NET Core MVC controller, use the validator to automatically validate models in HTTP requests
public class PersonController : ControllerBase
{
private readonly IValidator<Person> _validator;
public PersonController(IValidator<Person> validator)
{
_validator = validator;
}
[HttpPost]
public IActionResult AddPerson([FromBody] Person person)
{
var validationResult = _validator.Validate(person);
if (!validationResult.IsValid)
{
return BadRequest(validationResult.Errors);
}
// If the model is valid, continue with the business logic
// ...
return Ok("Person added successfully.");
}
}
8. IdentityServer
它是 ASP.NET Core 中用于身份验证和授权的库。它支持 OAuth2 和 OpenID Connect,集中用户身份管理、身份验证和访问控制。这通过为安全身份验证和授权提供统一的平台来简化开发。借助 IdentityServer,开发人员可以高效地处理身份验证、管理授权策略并保护对资源的访问,从而增强 ASP.NET Core 应用程序的安全性。
// Install IdentityServer4 package via NuGet
// Install-Package IdentityServer4
using IdentityServer4;
using IdentityServer4.Models;
using System.Collections.Generic;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Configure IdentityServer
services.AddIdentityServer()
.AddInMemoryClients(new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
})
.AddInMemoryApiScopes(new List<ApiScope>
{
new ApiScope("api1", "My API")
})
.AddInMemoryApiResources(new List<ApiResource>())
.AddDeveloperSigningCredential(); // Use in-memory signing key for development
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseIdentityServer();
}
}
9. Polly
它是一个 .NET 库,用于增强服务复原能力和容错能力。它提供重试和断路器等策略来有效处理故障。开发人员使用 Polly 来解决网络问题、服务不可用或意外错误。例如,重试策略重试失败的操作,帮助服务从暂时性故障中恢复。断路器策略可防止重复失败的尝试,从而允许服务在设定的时间后恢复运行。通过利用 Polly,开发人员可以创建能够承受故障场景、增强系统稳定性和性能的强大应用程序。
// Import the necessary Polly namespaces
using Polly;
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Define a policy for retrying failed operations
var retryPolicy = Policy.Handle<HttpRequestException>()
.WaitAndRetryAsync(3, _ => TimeSpan.FromSeconds(1));
// Define a policy for circuit breaking
var circuitBreakerPolicy = Policy.Handle<HttpRequestException>()
.CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
// Example usage of retry policy
await retryPolicy.ExecuteAsync(async () =>
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://api.example.com");
response.EnsureSuccessStatusCode();
Console.WriteLine("Request successful!");
});
// Example usage of circuit breaker policy
await circuitBreakerPolicy.ExecuteAsync(async () =>
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://api.example.com");
response.EnsureSuccessStatusCode();
Console.WriteLine("Request successful!");
});
}
}
10. XUnit
它是一个主要用于 .NET 生态系统的单元测试库。它使开发人员能够编写和执行单元测试,以验证各个代码单元的功能。遵循测试驱动的开发原则,XUnit 强调简单性、灵活性和可扩展性。它提供测试发现、执行、设置/拆解方法、参数化测试、测试类别和输出捕获等功能。XUnit 通过鼓励使用属性来标记测试方法和将测试问题分离到单独的类中等约定来促进干净和可读的测试代码。
// Example of a simple xUnit test class
using Xunit;
public class MathOperationsTests
{
// Example of a test method
[Fact]
public void Add_TwoNumbers_ReturnsSum()
{
// Arrange
int a = 5;
int b = 10;
// Act
int result = MathOperations.Add(a, b);
// Assert
Assert.Equal(15, result);
}
// Example of a parameterized test method
[Theory]
[InlineData(3, 5, 8)]
[InlineData(0, 0, 0)]
[InlineData(-1, 1, 0)]
public void Add_TwoNumbers_ReturnsCorrectSum(int a, int b, int expected)
{
// Act
int result = MathOperations.Add(a, b);
// Assert
Assert.Equal(expected, result);
}
}
// Example of a class with methods to be tested
public class MathOperations
{
public static int Add(int a, int b)
{
return a + b;
}
}
- 上一篇:机器学习中英文对照表
- 下一篇:核心名词function的一个重要用法
相关推荐
- 史上最全的浏览器兼容性问题和解决方案
-
微信ID:WEB_wysj(点击关注)◎◎◎◎◎◎◎◎◎一┳═┻︻▄(页底留言开放,欢迎来吐槽)●●●...
-
- 平面设计基础知识_平面设计基础知识实验收获与总结
-
CSS构造颜色,背景与图像1.使用span更好的控制文本中局部区域的文本:文本;2.使用display属性提供区块转变:display:inline(是内联的...
-
2025-02-21 16:01 yuyutoo
- 写作排版简单三步就行-工具篇_作文排版模板
-
和我们工作中日常word排版内部交流不同,这篇教程介绍的写作排版主要是用于“微信公众号、头条号”网络展示。写作展现的是我的思考,排版是让写作在网格上更好地展现。在写作上花费时间是有累积复利优势的,在排...
- 写一个2048的游戏_2048小游戏功能实现
-
1.创建HTML文件1.打开一个文本编辑器,例如Notepad++、SublimeText、VisualStudioCode等。2.将以下HTML代码复制并粘贴到文本编辑器中:html...
- 今天你穿“短袖”了吗?青岛最高23℃!接下来几天气温更刺激……
-
最近的天气暖和得让很多小伙伴们喊“热”!!! 昨天的气温到底升得有多高呢?你家有没有榜上有名?...
- CSS不规则卡片,纯CSS制作优惠券样式,CSS实现锯齿样式
-
之前也有写过CSS优惠券样式《CSS3径向渐变实现优惠券波浪造型》,这次再来温习一遍,并且将更为详细的讲解,从布局到具体样式说明,最后定义CSS变量,自定义主题颜色。布局...
- 你的自我界限够强大吗?_你的自我界限够强大吗英文
-
我的结果:A、该设立新的界限...
- 行内元素与块级元素,以及区别_行内元素和块级元素有什么区别?
-
行内元素与块级元素首先,CSS规范规定,每个元素都有display属性,确定该元素的类型,每个元素都有默认的display值,分别为块级(block)、行内(inline)。块级元素:(以下列举比较常...
-
- 让“成都速度”跑得潇潇洒洒,地上地下共享轨交繁华
-
去年的两会期间,习近平总书记在参加人大会议四川代表团审议时,对治蜀兴川提出了明确要求,指明了前行方向,并带来了“祝四川人民的生活越来越安逸”的美好祝福。又是一年...
-
2025-02-21 16:00 yuyutoo
- 今年国家综合性消防救援队伍计划招录消防员15000名
-
记者24日从应急管理部获悉,国家综合性消防救援队伍2023年消防员招录工作已正式启动。今年共计划招录消防员15000名,其中高校应届毕业生5000名、退役士兵5000名、社会青年5000名。本次招录的...
- 一起盘点最新 Chrome v133 的5大主流特性 ?
-
1.CSS的高级attr()方法CSSattr()函数是CSSLevel5中用于检索DOM元素的属性值并将其用于CSS属性值,类似于var()函数替换自定义属性值的方式。...
- 竞走团体世锦赛5月太仓举行 世界冠军杨家玉担任形象大使
-
style="text-align:center;"data-mce-style="text-align:...
- 学物理能做什么?_学物理能做什么 卢昌海
-
作者:曹则贤中国科学院物理研究所原标题:《物理学:ASourceofPowerforMan》在2006年中央电视台《对话》栏目的某期节目中,主持人问过我一个的问题:“学物理的人,如果日后不...
-
- 你不知道的关于这只眯眼兔的6个小秘密
-
在你们忙着给熊本君做表情包的时候,要知道,最先在网络上引起轰动的可是这只脸上只有两条缝的兔子——兔斯基。今年,它更是迎来了自己的10岁生日。①关于德艺双馨“老艺...
-
2025-02-21 16:00 yuyutoo
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- mybatis plus (70)
- scheduledtask (71)
- css滚动条 (60)
- java学生成绩管理系统 (59)
- 结构体数组 (69)
- databasemetadata (64)
- javastatic (68)
- jsp实用教程 (53)
- fontawesome (57)
- widget开发 (57)
- vb net教程 (62)
- hibernate 教程 (63)
- case语句 (57)
- svn连接 (74)
- directoryindex (69)
- session timeout (58)
- textbox换行 (67)
- extension_dir (64)
- linearlayout (58)
- vba高级教程 (75)
- iframe用法 (58)
- sqlparameter (59)
- trim函数 (59)
- flex布局 (63)
- contextloaderlistener (56)