Microsoft 的 .NET Core 生态系统中的中间件已经发生了重大变化,包括无缝集成到应用程序管道中的内置和第三方组件,协调客户端和服务器之间的数据流。它通过身份验证、日志记录和路由等功能增强了应用程序功能,确保了可扩展性和可维护性
我将展示 Microsoft 的十种出色的中间件解决方案。无论你是经验丰富的开发人员还是 .NET Core 新手,此探索都提供了宝贵的见解和资源来增强你的开发项目。
它是软件开发中的一个库,可简化不同对象类型之间的数据传输。开发人员无需手动复制每个属性,而是通过简单的配置过程定义映射。这种自动化可以节省时间,减少错误,并增强代码的可读性和可维护性。通过消除手动任务,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 文档的创建。其主要功能包括:
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($"Timestamp: {log.Timestamp}, Level: {log.Level}, Message: {log.MessageTemplate.Text}");
}
// Dispose the logger
Log.CloseAndFlush();
}
}
5. NancyFx
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;
}
}