locked
ASP.NET - Web API - [DataMember] an array of three types RRS feed

  • Question

  • User-1608281605 posted

    Hi all;

    I have a REST web service implemented using ASP.NET Web API. I need to add a call to join documents. So this call is passed up an array of documents, they are joined in the passed in order, and then a single document is returned.

    The problem is the documents can be passed in three different ways.

    1. The actual file passed as a base64 encoded copy of the bits.
    2. A url to the file.
    3. A guid that identifies a file we have stored.

    So what I need is something like:

    [DataMember]
    public Data | Url | Guid [] Files { get; set; }

    Or to put it as XML:

    <files>
      <Data>01034f2d...</Data>
      <Url>http://data.files.com/mystuff/HiThere.pdf</Url>
      <Guid>38D2C12D-6D6D-4353-A8BD-A8B09DB177EF</Guid>
      <Url>http://data.files.com/mystuff/HelloThere.pdf</Url>
      <Guid>C6501830-18E6-4A76-BA13-96D5BE031D5A</Guid>
    </files>

    The problem is the ordering - I can't have this because it doesn't allow ordering between types:

    [DataMember]
    public string [] Data { get; set; }
    [DataMember]
    public string [] Url { get; set; }
    [DataMember]
    public string [] Guid { get; set; }

    How can I do this?

    thanks - dave

    Friday, April 17, 2020 12:09 PM

All replies

  • User475983607 posted

    One solution is sending the type along with the data.  The client code must know what types to expect so the client knows how to deserialize the type.  An enum is a better option for the type to expect.

    public class GenericStringDataType 
    {
    	public string TypeToExpect {get; set;}
    	public string[] Files { get; set; }
    	
    }

    A much better approach is creating three API endpoints that returns each type explicitly.  No matter how you look at the problem, the client needs to know what type to expect.  It's mush easier for the client to request the type (since the client already knows what types are available) rather than trying to figure out what type returned.  This approach is a lot less code, easier to maintain code, and the approach follows standard SOLID principles.

    Friday, April 17, 2020 12:37 PM
  • User-474980206 posted

    c# does not support xml / json variants well. you will need a custom serializer. 

    [DataMember]
    public object [] Files {get set;}

    Monday, April 20, 2020 3:09 PM