ZetCode

ASP.NET Action

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 ASP.NET 8 中的 Action 委托。Action 是一种内置的委托类型,可简化方法的封装和调用。

ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。Action 委托通常用于回调和事件处理程序。

基本定义

NET 中的 Action 委托表示一个带参数但不返回值的方法。它是 System 命名空间的一部分,并且有泛型变体。

Action 可以封装最多 16 个参数的方法。非泛型 Action 委托表示一个没有参数的方法,而 Action表示一个带单个参数的方法。

在 ASP.NET 中,Action 委托常用于中间件、请求管道和定义内联方法。它们为方法调用提供了灵活性。

ASP.NET Action 示例

以下示例演示了在 ASP.NET 8 应用程序中使用 Action 委托。

Program.cs
var builder = WebApplication.CreateBuilder(args);

// Register a service that uses Action
builder.Services.AddSingleton<NotificationService>();
builder.Services.AddTransient<EmailNotifier>();
builder.Services.AddTransient<SmsNotifier>();

var app = builder.Build();

// Middleware using Action
app.Use(async (context, next) =>
{
    var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Request started at {Time}", DateTime.Now);
    
    // Action as a callback
    Action<string> logAction = message => 
        logger.LogInformation("Middleware log: {Message}", message);
    
    logAction("Processing request...");
    
    await next.Invoke();
    
    logAction("Request completed");
});

app.MapGet("/notify", (NotificationService service) =>
{
    // Using Action as parameter
    service.SendNotification("Important system update", notifier =>
    {
        notifier.Notify("Admin", "Notification sent via callback");
    });
    
    return "Notification processed";
});

app.Run();

这会设置一个 ASP.NET 应用程序,演示在中间件和服务的 Action 用法。中间件以日志记录为目的展示了 Action 作为回调。

Services/NotificationService.cs
public class NotificationService
{
    private readonly EmailNotifier _emailNotifier;
    private readonly SmsNotifier _smsNotifier;

    public NotificationService(EmailNotifier emailNotifier, SmsNotifier smsNotifier)
    {
        _emailNotifier = emailNotifier;
        _smsNotifier = smsNotifier;
    }

    public void SendNotification(string message, Action<INotifier> callback)
    {
        // Process notification
        Console.WriteLine($"Sending notification: {message}");
        
        // Use Action callback
        callback(_emailNotifier);
        callback(_smsNotifier);
        
        Console.WriteLine("Notification processing complete");
    }
}

public interface INotifier
{
    void Notify(string recipient, string message);
}

public class EmailNotifier : INotifier
{
    public void Notify(string recipient, string message)
    {
        Console.WriteLine($"Email to {recipient}: {message}");
    }
}

public class SmsNotifier : INotifier
{
    public void Notify(string recipient, string message)
    {
        Console.WriteLine($"SMS to {recipient}: {message}");
    }
}

此服务演示了将 Action 作为方法参数。SendNotification 方法接受一个消息和一个对 INotifier 操作的 Action 委托。

回调 Action 被调用两次——一次使用 EmailNotifier,一次使用 SmsNotifier。这表明 Action 如何封装不同的行为。

该示例说明了几个 Action 用例:作为中间件回调、作为用于灵活行为的方法参数,以及与接口实现。

来源

Microsoft Action Delegate 文档

在本文中,我们探讨了 ASP.NET 8 中的 Action 委托。这个功能强大的特性支持灵活的方法封装和回调场景。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 ASP.NET 教程