Home > OS >  How to customs an attribute in .net?
How to customs an attribute in .net?

Time:08-04

I have created an attribute for replace special character.

My class customs:

  public class CleanInjectionAttribute : Attribute
    {
        public string? StringValue
        {
            get
            {
                throw null;
            }
            set
            {
            }
        }

        public string ReplaceCharacter(object stringValue)
        {
            string result = stringValue as string;
            if (!string.IsNullOrEmpty(result))
            {
                if (result.Contains("<"))
                    result = result.Replace("<", "&lt;");

                if (result.Contains(">"))
                    result = result.Replace(">", "&gt;");

                if (result.Contains("&"))
                    result = result.Replace("&", "&amp;");

                if (result.Contains("\""))
                    result = result.Replace("\"", "&quot;");
            }

            return result;
        }
    }

My property can using that attribute. But it not call to ReplaceCharacter function in class CleanInjectionAttribute.

[CleanInjection]
public string InputField { get; set; }

I want whenever property InputField receives a value and it contains special characters, it will change those special characters.

Example:

The input value by me <html>Html Injection</html>

The return value I want &lt;html&gt;Html Injection&lt;/html&gt;

CodePudding user response:

What you are trying to do is not supported in attributes offered by .net framework. Attributes are kind of metadata which can be read during runtime only and then execute any operation based on attribute values provided. But what you are trying is to execute some action in attribute when prop changes that's not possible. You can leverage setter of property, getting rid of attribute.

  • Related