Exposing the DescriptionAttribute of Enums from a WCF Service

后端 未结 3 929
予麋鹿
予麋鹿 2021-01-22 11:58

how can i expose description attribute in enum values from service to client or web reference using WCF or

how can i expose enum with description attribute to client

相关标签:
3条回答
  • 2021-01-22 12:50

    You can't force this - the mex/WDSL descriptors only contain a tiny subset of the information associated with a type.

    If you control the client, one option is to declare the enum (or even all the types) locally, and consume from there. You should be able to use the svcutil /reference: switch to use types from an existing assembly (the IDE offers the same). But note that this partly breaks the rules of SOA (i.e. you are using more information than the service contract promises).

    0 讨论(0)
  • 2021-01-22 12:54

    you can do this using reflection. back in the client after you have the Enum value.. try picking up the attribute using GetField() & GetCustomAttributes()

    using System;
    using System.Reflection;
    using System.ComponentModel;
    
    namespace CustomAttributes
    {
        class Program
        {
            static void Main(string[] args)
            {
                Colors n1 = Colors.blue;
    
                object [] attribues = n1.GetType().GetField(n1.ToString()).GetCustomAttributes(true);
                Console.WriteLine((attribues[0] as DescriptionAttribute).Description);
                // WOULD PRINT  "DARK BLUE"
            }
        }
    
        enum Colors
        {
            [Description("DARK BLUE")]
            blue,
            [Description("PLAIN WHITE")]
            white
        }
    }
    
    0 讨论(0)
  • 2021-01-22 12:59

    Check out the XmlEnum Attribute. That will allow you to specify the "Name" of the xml attribute. Eg:

    public enum MyEnum
    {
        [XmlEnum("Coolbox")]
        Esky,
        [XmlEnum("Sandles")]
        Thong,
        [XmlEnum("MoreLikeGridironThanRealFootball")]
        Footy,
    }
    
    0 讨论(0)
提交回复
热议问题