Member-only story
Using Attributes in ASP.NET Core
In C# and ASP.NET Core, attributes are a structure used to mark classes, methods, properties, parameters, or other code elements with additional information. Attributes provide metadata, which can be read by other code during runtime or at compile time.
What is an Attribute?
An attribute in the C# programming language is a type of class and is typically used within square brackets ([ ]). In ASP.NET Core, attributes are used in scenarios such as:
Model validation: e.g., [Required], [StringLength]
Authorization and security: e.g., [Authorize]
Middleware or framework configuration: e.g., [HttpGet], [HttpPost]
Defining and Using Attributes
An attribute is written inside square brackets ([ ]) and placed above the targeted code element.
Creating a Custom Attribute
You can define and use your own custom attributes. For example, let’s create an attribute to mark a method for logging.
using System;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class LogAttribute : Attribute
{
public string LogMessage { get; }
public LogAttribute(string message)
{
LogMessage = message;
}
}
Usage Example:
public class HomeController
{
[Log("This is a log message.")]
public void ExampleMethod()…