Thursday, March 31, 2011

Exposing the DescriptionAttribute of Enums from a WCF Service

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 using WCF? while exposing Description attribute is not exposed only enum values are exposed in client. I want value in description attribue in enums.

From stackoverflow
  • 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
        }
    }
    
    Marc Gravell : This doesn't apply to the generated WCF proxy, since [Description] doesn't transfer
  • 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,
    }
    
  • 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 comments:

Post a Comment