.NET Core 中推荐使用的10大优秀库,你用到过几个?
ztj100 2024-12-25 16:49 16 浏览 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;
}
}
相关推荐
- 使用Python编写Ping监测程序(python 测验)
-
Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;本文将介绍如何使用Python编写Ping监测程...
- 批量ping!有了这个小工具,python再也香不了一点
-
号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友。在咱们网工的日常工作中,经常需要检测多个IP地址的连通性。不知道你是否也有这样的经历:对着电脑屏...
- python之ping主机(python获取ping结果)
-
#coding=utf-8frompythonpingimportpingforiinrange(100,255):ip='192.168.1.'+...
- 网站安全提速秘籍!Nginx配置HTTPS+反向代理实战指南
-
太好了,你直接问到重点场景了:Nginx+HTTPS+反向代理,这个组合是现代Web架构中最常见的一种部署方式。咱们就从理论原理→实操配置→常见问题排查→高级玩法一层层剖开说,...
- Vue开发中使用iframe(vue 使用iframe)
-
内容:iframe全屏显示...
- Vue3项目实践-第五篇(改造登录页-Axios模拟请求数据)
-
本文将介绍以下内容:项目中的public目录和访问静态资源文件的方法使用json文件代替http模拟请求使用Axios直接访问json文件改造登录页,配合Axios进行登录请求,并...
- Vue基础四——Vue-router配置子路由
-
我们上节课初步了解Vue-router的初步知识,也学会了基本的跳转,那我们这节课学习一下子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只...
- Vue3.0权限管理实现流程【实践】(vue权限管理系统教程)
-
作者:lxcan转发链接:https://segmentfault.com/a/1190000022431839一、整体思路...
- swiper在vue中正确的使用方法(vue中如何使用swiper)
-
swiper是网页中非常强大的一款轮播插件,说是轮播插件都不恰当,因为它能做的事情太多了,swiper在vue下也是能用的,需要依赖专门的vue-swiper插件,因为vue是没有操作dom的逻辑的,...
- Vue怎么实现权限管理?控制到按钮级别的权限怎么做?
-
在Vue项目中实现权限管理,尤其是控制到按钮级别的权限控制,通常包括以下几个方面:一、权限管理的层级划分...
- 【Vue3】保姆级毫无废话的进阶到实战教程 - 01
-
作为一个React、Vue双修选手,在Vue3逐渐稳定下来之后,是时候摸摸Vue3了。Vue3的变化不可谓不大,所以,本系列主要通过对Vue3中的一些BigChanges做...
- Vue3开发极简入门(13):编程式导航路由
-
前面几节文章,写的都是配置路由。但是在实际项目中,下面这种路由导航的写法才是最常用的:比如登录页面,服务端校验成功后,跳转至系统功能页面;通过浏览器输入URL直接进入系统功能页面后,读取本地存储的To...
- vue路由同页面重定向(vue路由重定向到外部url)
-
在Vue中,可以使用路由的重定向功能来实现同页面的重定向。首先,在路由配置文件(通常是`router/index.js`)中,定义一个新的路由,用于重定向到同一个页面。例如,我们可以定义一个名为`Re...
- 那个 Vue 的路由,路由是干什么用的?
-
在Vue里,路由就像“页面导航的指挥官”,专门负责管理页面(组件)的切换和显示逻辑。简单来说,它能让单页应用(SPA)像多页应用一样实现“不同URL对应不同页面”的效果,但整个过程不会刷新网页。一、路...
- Vue3项目投屏功能开发!(vue投票功能)
-
最近接了个大屏项目,产品想在不同的显示器上展示大屏项目不同的页面,做出来的效果图大概长这样...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)