In this lesson, you will learn how to use C# attributes to decorate your Blazor components, allowing you to build automated processing logic that treats your UI as data.
Beyond Parameters
While [Parameter] attributes are how we pass data into components, custom attributes allow us to attach "extra" information to components—metadata that isn’t strictly for the UI, but for the infrastructure handling the component. Think of these as labels you stick on a component class that a specialized service can read via reflection to make decisions.
Practical Example: Automated Permissions
Imagine you want to log usage or enforce authorization automatically whenever a specific component is rendered. Instead of manual checks in every OnInitialized, you can define a custom attribute:
[AttributeUsage(AttributeTargets.Class)]
public class FeaturePermissionAttribute : Attribute
{
public string RequiredRole { get; }
public FeaturePermissionAttribute(string role) => RequiredRole = role;
}
[FeaturePermission("AdminOnly")]
public partial class AdminDashboard : ComponentBase { ... }
Reflecting on Components
To make this useful, you create a "processor" or a base layout component that scans the active component type at runtime. By using typeof(ComponentType).GetCustomAttribute<FeaturePermissionAttribute>(), you can extract that metadata.
If you find the attribute, your logic can automatically block rendering, show an "Access Denied" state, or record telemetry—all without writing a single line of explicit code inside the AdminDashboard component itself.
Why this matters
This pattern decouples your business logic from your UI concerns. It keeps your components clean (the "Separation of Concerns" principle) because the component only declares what it is, while the surrounding framework handles how to treat it based on that metadata. This is highly effective for building modular systems where plugins or dynamic modules are added to your Blazor app, as the system can "self-discover" the capabilities of each component just by looking at its attributes.
Key Takeaway: Custom attributes act as declarative metadata that allows your infrastructure to dynamically discover and manage component behavior through reflection, keeping your component code focused purely on rendering.