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

  • SEARCH
  • Home
  • 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 7944481
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T00:33:51+00:00 2026-06-04T00:33:51+00:00

I have a Web API controller action which has a parameter of type CommandMessage.

  • 0

I have a Web API controller action which has a parameter of type CommandMessage. That type has a list with base types, CommandBase. My problem is that I can’t make them to be of derived types, MyCommand in this example.

I’m using JsonNetFormatter from the Web API contrib project. It’s using Json.Net as serializer.

Web API controller:

public class CommandController : ApiController
{
    public HttpResponseMessage Post(CommandMessage command)
    {
        //command.Commands[0].GetType().Name is always "CommandBase" instead of "MyCommand"
        var message = new HttpResponseMessage(HttpStatusCode.OK)
                          {
                              Content = new StringContent(string.Format("Type of command 1 is '{0}'", command.Commands[0].GetType().FullName))
                          };
        return message;
    }
}

This i my request:

private void When()
    {
        using (client)
        {
            command = new MyCommand
                          {
                              CommandId = Guid.NewGuid(),
                              Id = Guid.NewGuid(),
                              Name = "Martin"
                          };

            var message = new CommandMessage(Guid.NewGuid(),new List<CommandBase> {command});

            var requestMessage = GetHttpRequestMessage(message);
            var task = client.PostAsync("http://localhost.:16218/api/command", requestMessage.Content);
            task.Wait();
            responseMessage = task.Result;
        }
    }

private static HttpRequestMessage GetHttpRequestMessage<T>(T data)
    {
        var mediaType = new MediaTypeHeaderValue("application/json");
        var jsonFormatter = new JsonNetFormatter(DefaultJsonSettings.Settings());

        var requestMessage = new HttpRequestMessage<T>(data, mediaType, new[] {jsonFormatter});

        return requestMessage;
    }

And as JSON:

{
  "$type": "PostToBaseClassList.Models.CommandMessage, PostToBaseClassList",
  "Commands": [
    {
      "$type": "PostToBaseClassList.Models.MyCommand, PostToBaseClassList",
      "Id": "45923a41-0c15-46e3-907d-64dd06840539",
      "Name": "Martin"
    }
  ],
  "MessageId": "c873970a-8621-4223-806e-b809039438ab"
}

The return message from the API controller action is:

Type of command 1 is ‘PostToBaseClassList.Models.CommandBase’

Command classes:

 [DataContract]
[XmlRoot]
public class MyCommand : CommandBase
{
    private readonly string name;

    public MyCommand()
    {
    }

    public MyCommand(Guid id, string name)
    {
        this.name = name;
        Id = id;
    }

    [DataMember(Order = 1)]
    [XmlElement]
    public Guid Id { get; set; }

    [DataMember(Order = 2)]
    [XmlElement]
    public string Name { get; set; }
}

 [DataContract]
[KnownType("GetKnownTypes")]
public class CommandBase
{
    public Guid CommandId { get; set; }

    public static Type[] GetKnownTypes()
    {
        var query =
            from type in typeof (CommandBase).Assembly.GetTypes()
            where typeof (CommandBase).IsAssignableFrom(type)
            select type;

        var types = query.ToArray();
        return types;
    }
}

[DataContract]
[Serializable]
[XmlRoot]
public class CommandMessage
{
    public CommandMessage()
    {
    }

    public CommandMessage(Guid messageId, IEnumerable<CommandBase> commands)
    {
        MessageId = messageId;
        Commands = new List<CommandBase>(commands);
    }

    [DataMember]
    [XmlElement]
    public List<CommandBase> Commands { get; set; }

    [DataMember]
    [XmlElement]
    public Guid MessageId { get; set; }
}

Json.Net settings:

//DefaultJsonSettings.Settings()
var settings = new JsonSerializerSettings
                           {
                               NullValueHandling = NullValueHandling.Ignore,
                               TypeNameHandling = TypeNameHandling.Objects,
                               Converters = new List<JsonConverter>
                                                {
                                                    new IsoDateTimeConverter
                                                        ()
                                                }
                           };

private static void RegisterFormatters(HttpConfiguration config)
    {
        var jsonNetFormatter = new JsonNetFormatter(DefaultJsonSettings.Settings());
        config.Formatters.Insert(0, jsonNetFormatter);
    }

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-04T00:33:53+00:00Added an answer on June 4, 2026 at 12:33 am

    It worked after I added this row to RegisterFormatters()

    config.Formatters.Remove(config.Formatters.JsonFormatter);
    

    This was not enough

    config.Formatters.Insert(0, jsonNetFormatter);
    

    Full version

    private void RegisterFormatters()
    {
        config.Formatters.Remove(config.Formatters.JsonFormatter);
        var jsonNetFormatter = new JsonNetFormatter(DefaultJsonSettings.Settings());
        config.Formatters.Insert(0, jsonNetFormatter);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple web service that has an API third party developers are
Let say I have two methods in MVC 4 Web API controller: public IQueryable<A>
I have a web API that returns python dictionaries or lists as a response
I have the following action in my ASP.NET Web API: public IEnumerable<Car> carssOfUser(int id,
I have a web site with an API which publishes the information using JSON.
I have an existing application that imports data from a web site api into
I have an API that services a web-based plugin for processing email. The API
I have a web API that I want to allow any domain to submit
My web-api controller has a GET method to search for domain availability with the
I have a web app with a clean RESTful JSON API, based on Rails

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.