百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

.NET Core 中推荐使用的10大优秀库,你用到过几个?

ztj100 2024-12-25 16:49 10 浏览 0 评论

概述:Microsoft 的 .NET Core 生态系统中的中间件已经发生了重大变化,包括无缝集成到应用程序管道中的内置和第三方组件,协调客户端和服务器之间的数据流。它通过身份验证、日志记录和路由等功能增强了应用程序功能,确保了可扩展性和可维护性我将展示 Microsoft 的十种出色的中间件解决方案。无论你是经验丰富的开发人员还是 .NET Core 新手,此探索都提供了宝贵的见解和资源来增强你的开发项目。AutoMapper它是软件开发中的一个库,可简化不同对象类型之间的数据传输。开发人员无需手动复制每个属性,而是通过简单的配置过程定义映射。这种自动化可以节省时间,减少错误,并增强代码的可读性

Microsoft 的 .NET Core 生态系统中的中间件已经发生了重大变化,包括无缝集成到应用程序管道中的内置和第三方组件,协调客户端和服务器之间的数据流。它通过身份验证、日志记录和路由等功能增强了应用程序功能,确保了可扩展性和可维护性

我将展示 Microsoft 的十种出色的中间件解决方案。无论你是经验丰富的开发人员还是 .NET Core 新手,此探索都提供了宝贵的见解和资源来增强你的开发项目。

  1. 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;
    }
}

相关推荐

Java项目宝塔搭建实战MES-Springboot开源MES智能制造系统源码

大家好啊,我是测评君,欢迎来到web测评。...

一个令人头秃的问题,Logback 日志级别设置竟然无效?

原文链接:https://mp.weixin.qq.com/s/EFvbFwetmXXA9ZGBGswUsQ原作者:小黑十一点半...

实战!SpringBoot + RabbitMQ死信队列实现超时关单

需求背景之为什么要有超时关单原因一:...

火了!阿里P8架构师编写堪称神级SpringBoot手册,GitHub星标99+

Springboot现在已成为企业面试中必备的知识点,以及企业应用的重要模块。今天小编给大家分享一份来着阿里P8架构师编写的...

Java本地搭建宝塔部署实战springboot仓库管理系统源码

大家好啊,我是测评君,欢迎来到web测评。...

工具尝鲜(1)-Fleet构建运行一个Springboot入门Web项目

Fleet是JetBrains公司推出的轻量级编辑器,对标VSCode。该款产品还在公测当中,具体下载链接如下JetBrainsFleet:由JetBrains打造的下一代IDE。想要尝试的...

SPRINGBOOT WEB 实现文件夹上传(保留目录结构)

网上搜到的SpringBoot的代码不多,完整的不多,能用的也不多,基本上大部分的文章只是提供了少量的代码,讲一下思路,或者实现方案。之前一般的做法都是使用HTML5来做的,大部都是传文件的,传文件夹...

Java项目本地部署宝塔搭建实战报修小程序springboot版系统源码

大家好啊,我是测评君,欢迎来到web测评。...

新年IT界大笑料“工行取得基于SpringBoot的web系统后端实现专利

先看看专利描述...

看完SpringBoot源码后,整个人都精神了

前言当读完SpringBoot源码后,被Spring的设计者们折服,Spring系列中没有几行代码是我们看不懂的,而是难在理解设计思路,阅读Spring、SpringMVC、SpringBoot需要花...

阿里大牛再爆神著:SpringBoot+Cloud微服务手册

今天给大家分享的这份“Springboot+Springcloud微服务开发实战手册”共有以下三大特点...

WebClient是什么?SpringBoot中如何使用WebClient?

WebClient是什么?WebClient是SpringFramework5引入的一个非阻塞、响应式的Web客户端库。它提供了一种简单而强大的方式来进行HTTP请求,并处理来自服务器的响应。与传...

SpringBoot系列——基于mui的H5套壳APP开发web框架

  前言  大致原理:创建一个main主页面,只有主页面有头部、尾部,中间内容嵌入iframe内容子页面,如果在当前页面进行跳转操作,也是在iframe中进行跳转,而如果点击尾部按钮切换模块、页面,那...

在Spring Boot中使用 jose4j 实现 JSON Web Token (JWT)

JSONWebToken或JWT作为服务之间安全通信的一种方式而闻名。...

Spring Boot使用AOP方式实现统一的Web请求日志记录?

AOP简介AOP(AspectOrientedProgramming),面相切面编程,是通过代码预编译与运行时动态代理的方式来实现程序的统一功能维护的方案。AOP作为Spring框架的核心内容,通...

取消回复欢迎 发表评论: