Explanation of C# Attribute

Posted by why2k on Fri, 07 Jan 2022 09:53:09 +0100

1. Introduction and use of features

An Attribute is a declarative label used to pass behavior information of various elements in a program (such as classes, methods, structures, enumerations, components, etc.) at run time. You can add declarative information to a program by using attributes. A declarative tag is described by square brackets ([]) placed before the element to which it applies.

The use method of the feature is very simple. You only need to write it on the method, class, enumeration, field and other program bodies and enclose it with [] as follows.

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController:ControllerBase
    {
        [HttpGet]
        [Obsolete]
        public void Test()
        {
            Console.WriteLine("This is an outdated method");
        }
    }

Multiple features are generally supported.

2. .Net comes with three predefined features

AttributeUsage
AttributeUsage is only valid for derived classes inherited from Attribute to control the scope of use of the current class. For example, in the following code, I defined a custom feature of TestUser and passed in attributetargets in the AttributeUsage parameter Method this parameter specifies that the current Attribute is only valid for methods.

 [AttributeUsage(AttributeTargets.Method)]
    class TestUserAttribute : Attribute
    {
       public static void Test()
       {
       }
    }

When I use this feature. It can only be defined on the method.

    [TestUser]
    static void Main(string[] args)
    {
        Test();
        Console.WriteLine("Hello, World!");
    }

If it is placed on other structures, an error will be reported.

If you need to specify that it is valid for multiple program bodies, write multiple targets here, separated by |, or specify attributetargets All indicates that it is valid for all program bodies.

//Valid only for methods and classes
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,AllowMultiple =true)]
class TestUserAttribute : Attribute
  {
     public static void Test()
     {
     }
  }
//Valid for all structures
[AttributeUsage(AttributeTargets.All,AllowMultiple =true)]
class TestUserAttribute : Attribute
  {
     public static void Test()
     {
     }
  }

AttributeTargets is an enumeration that includes the following.

Obsolete
This feature can be used to declare that the program body is obsolete and deprecated.

  [Obsolete("This method is obsolete, please use TestNew",true)]
  static void Test()
    {
        Console.WriteLine("This is an outdated method");
    }
    static void TestNew()
    {
        Console.WriteLine("This is the latest method");
    }

Obsolete has three overloads.
ObsoleteAttribute() indicates that the body is deprecated.
ObsoleteAttribute(string? message) can enter prompt content and display it when the mouse moves over the program body name.
The ObsoleteAttribute(string? message, bool error) bool parameter is used to indicate whether the method is discarded. If it is true, the program body cannot be used. The default is false

Conditional
Conditional is located in system Diagnostics namespace
This specific condition determines whether to run the corresponding program body below through judgment. For example, as follows, I passed a string Debug, but did not define this string, so this method will not be executed.

If Debug is defined at the top, this method will execute.

3. Common features

In the namespace Microsoft AspNetCore. Under MVC, there are many well-defined features. Next, I will briefly introduce some common features Net core version 3.1.
RouteAttribute
Scope: Class, Method
Description: create a new route using the given route template.
ApiControllerAttribute
Scope: Assembly, Class
Description: indicates that HTTP API responses are provided using types and all derived types.
HttpGetAttribute
Scope: All
Description: identifies operations that support HTTP GET methods.
HttpPostAttribute
Scope: All
Description: identifies operations that support HTTP POST methods.
HttpPutAttribute
Scope: All
Description: identifies operations that support HTTP PUT methods.
HttpDeleteAttribute
Scope: All
Description: identifies the operation that supports the HTTP DELETE method.
FromBodyAttribute
Scope: Property,Parameter
Description: Specifies that the request body should be used to bind parameters or properties.
FromFormAttribute
Scope: Property,Parameter
Description: Specifies that form data binding parameters or properties should be used in the request body.
FromHeaderAttribute
Scope: Property,Parameter
Description: Specifies that the request header should be used to bind parameters or properties.
FromQueryAttribute
Scope: Property,Parameter
Description: Specifies that the request query string should be used to bind parameters or properties.
FromRouteAttribute
Scope: Property,Parameter
Description: Specifies that the route data in the current request should be used to bind parameters or attributes.
FromServicesAttribute
Scope: Parameter
Description: Specifies that the request service binding operation parameters should be used.
ActionContextAttribute
Scope: Property
Description: Specifies that the currently set controller property ActionContext should be used when creating the controller. The property must have a common set method.
ActionNameAttribute
Scope: Method
Description: Specifies the name of the operation.
AreaAttribute
Scope: class, method
Description: Specifies the area containing the controller or operation.
ControllerAttribute
Scope: Class
Description: indicates that the type to which this attribute is applied and any derived types are treated as controllers by the default controller discovery mechanism, unless the NonControllerAttribute is applied to any type in the hierarchy.
ControllerContextAttribute
Scope: Property
Description: Specifies that the controller property ControllerContext currently set should be used when creating the controller. The property must have a common set method.
FormatFilterAttribute
Scope: Class,Method
Description: a filter that sets the content type of the ObjectResult returned from the operation using the format value in the routing data or query string.

4. Custom properties

Let's still use it NET web project, write a method to catch exceptions with features. First, define a property class. Inherited from Attribute and IExceptionFilter.
CatchExceptionAttribute.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Nlog_demo
{
    public class CatchExceptionAttribute : Attribute, IExceptionFilter
    {
        public CatchExceptionAttribute()  
        {
        }
        /// <summary>
        ///Abnormal entry
        /// </summary>
        /// <param name="context"></param>
        public async void OnException(ExceptionContext context)
        {
             ContentResult result = new ContentResult
            {
                StatusCode = 500,
                ContentType = "text/json;charset=utf-8;"
            };
            result.Content = "Oh, something's wrong.";
            context.Result = result;
            context.ExceptionHandled = true;
        }
    }
}

Then register in the status.

builder.Services.AddScoped<CatchExceptionAttribute>();

Then it can be used in the method. Just add the feature name to the method. The following code string to int will definitely report an error.

 [CatchException]
 public IActionResult Index()
  {
      var a = "hello world";
      var b = Convert.ToInt32(a);
      return View();
  }

The operation effect is as follows.

The project reports an error, and the console also prints an output. If you don't want such a prompt on the page, you can
The OnException method is modified as follows.

  public async void OnException(ExceptionContext context)
  {
        ContentResult result = new ContentResult
        {
            StatusCode = 500,
            ContentType = "text/json;charset=utf-8;"
        };
        result.Content = "Oh, something's wrong.";
        context.Result = result;
        context.ExceptionHandled = true;
    }

Run again to see the effect.

This page prompt is the effect after processing.

Study hard and make progress every day.

Topics: C# Attribute csharp