Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9006547
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T01:26:24+00:00 2026-06-16T01:26:24+00:00

I’m trying to create a generic function that when given an Enum Type will

  • 0

I’m trying to create a generic function that when given an Enum Type will return an object that when serialized by WebApi will provide nice looking output as XML/Json.

This method works perfectly fine when serialized as JSON, but I’m unable to get it working with XML. If I serialize the returned object manually with either an XmlSerializer or DataContractSerializer, I get results as expected. When WebApi itself tries to serialize it on the other hand from an HttpRequest, I get errors like the following:

System.Runtime.Serialization.SerializationException

Type ‘Priority’ with data contract name
‘Priority:http://schemas.datacontract.org/2004/07/’ is not expected.
Consider using a DataContractResolver or add any types not known
statically to the list of known types – for example, by using the
KnownTypeAttribute attribute or by adding them to the list of known
types passed to DataContractSerializer.

I’ve tried using GlobalConfiguration.Configuration.Formatters.XmlFormatter.SetSerializer to set the serializer for the generated type that I know works from setting breakpoints, but it just seems to ignore it and throws the same exception. The enums will be backed by integers and are guaranteed to have unique values for each entry. Here’s the code I’m using to generate the type and return an instance of it.

public object GetSerializableEnumProxy( Type enumType ) {

    if ( enumType == null ) {
        throw new ArgumentNullException( "enumType" );
    }

    if ( !enumType.IsEnum ) {
        throw new InvalidOperationException();
    }

    AssemblyName assemblyName = new AssemblyName("DataBuilderAssembly");
    AssemblyBuilder assemBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
    ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("DataBuilderModule");
    TypeBuilder typeBuilder = moduleBuilder.DefineType( enumType.Name, TypeAttributes.Class | TypeAttributes.Public );

    // Add the [DataContract] attribute to our generated type
    typeBuilder.SetCustomAttribute(
        new CustomAttributeBuilder( typeof(DataContractAttribute).GetConstructor( Type.EmptyTypes ), new object[] {} )
    );

    CustomAttributeBuilder dataMemberAttributeBuilder = new CustomAttributeBuilder(
        typeof(DataMemberAttribute).GetConstructor(Type.EmptyTypes), new object[] {}
    );

    // For each name in the enum, define a corresponding public int field
    // with the [DataMember] attribute
    foreach ( var value in Enum.GetValues(enumType).Cast<int>() ) {
        var name = Enum.GetName( enumType, value );

        var fb = typeBuilder.DefineField( name, typeof(int), FieldAttributes.Public );

        // Add the [DataMember] attribute to the field
        fb.SetCustomAttribute( dataMemberAttributeBuilder );

        // Set the value of our field to be the corresponding value from the Enum
        fb.SetConstant( value );
    }       

    // Return an instance of our generated type
    return Activator.CreateInstance( typeBuilder.CreateType() );
}

Web Api Controller Method:

private static IEnumerable<Type> RetrievableEnums = new Type[] {
    typeof(Priority), typeof(Status)
};

[GET("enum/{enumName}")]
public HttpResponseMessage GetEnumInformation( string enumName ) {

    Type enumType = RetrievableEnums.SingleOrDefault( type =>
        String.Equals( type.Name, enumName, StringComparison.InvariantCultureIgnoreCase));

    if ( enumType == null ) {
        return Request.CreateErrorResponse( HttpStatusCode.NotFound, "The requested enum could not be retrieved" );
    }

    return Request.CreateResponse( HttpStatusCode.OK, GetSerializableEnumProxy(enumType) );
}

Any ideas?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T01:26:25+00:00Added an answer on June 16, 2026 at 1:26 am

    I believe this is ultimately because you’re sending the enum value as an object – and unlike the Json formatter, Web API’s xml formatter, which uses DataContractSerializer, uses (in effect) the compile-time type of the value being serialized, not the runtime type.

    As a result, you must always make sure that any derived types of a base that you’re trying to serialize are added to the underlying serializer’s known types. In this case you have the dynamic enum (which is an object, of course).

    On the face of it, it seems that the SetSerializer(type, serializer) approach should work, however, I’ll bet your calling it with the dynamic type as the first argument – which won’t work if you are sending the enum out as object – because it’s the object serializer that the XmlRequestFormatter will use.

    This is a well-known issue – and one which I’ve reported as an issue on codeplex (there’s a good example there which demonstrates the problem in a simpler scenario).

    That issue also includes some C# code for an attribute and replacement for XmlMediaTypeFormatter (called XmlMediaTypeFormatterEx) that provides one solution to this problem – it uses a declarative per-operation approach. Replace the XmlMediaTypeFormatter with the one in the code – using something like this (note this code handles the case where there is no XML formatter already defined – perhaps somewhat pointlessly):

    var configuration = GlobalConfiguration.Configuration;  
    var origXmlFormatter = configuration.Formatters.OfType<XmlMediaTypeFormatter>()
                           .SingleOrDefault();
    
    XmlMediaTypeFormatterEx exXmlFormatter = new XmlMediaTypeFormatterEx(origXmlFormatter);
    
    if (origXmlFormatter != null)
    {
        configuration.Formatters.Insert(
          configuration.Formatters.IndexOf(origXmlFormatter), exXmlFormatter);
        configuration.Formatters.Remove(origXmlFormatter);
    }
    else
        configuration.Formatters.Add(exXmlFormatter);
    

    And now on the API method that you want to return this dynamic enum you’d decorate it with this:

    [XmlUseReturnedUnstanceType]
    public object Get()
    {
    
    }
    

    Now, whatever type you return from the Get method, the custom formatter kicks in and uses a DataContractSerializer specifically for the runtime type, not object.

    This doesn’t handle enumerables or dictionaries of bases – it gets very complicated then – but for basic single-instance return values it works fine.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need a function that will clean a strings' special characters. I do NOT
I'm trying to create an if statement in PHP that prevents a single post
Basically, what I'm trying to create is a page of div tags, each has
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.