[MyCustomAttribute("Example")] public class MyClass {} var type = typeof(MyClass); var attribute = type.GetCustomAttribute(typeof(MyCustomAttribute)) as MyCustomAttribute; if (attribute != null) { Console.WriteLine(attribute.Name); }
public class MyController { [HttpMethod("GET", "/")] public void Index() {} } var method = typeof(MyController).GetMethod("Index"); var attribute = method.GetCustomAttribute(typeof(HttpMethod)) as HttpMethod; if (attribute != null) { Console.WriteLine(attribute.Method + " " + attribute.Path); }In this example, the GetCustomAttribute method is called on the Index method of the MyController class to get the custom attribute of type HttpMethod. If the attribute is present, its Method and Path properties are printed to the console. Package Library: This method is a part of the System.Reflection namespace in the .NET core library.