Search code examples
angular.net-corekeyvaluepairhttp-put

What is the correct syntax to PUT serialize angular KeyValue to ASP.NET KeyValuePair?


I was trying to serialize a KeyValue "Array" to send it via PUT over http to my asp.net webserver.

The function in Angular looks like this:

SortAboutUs(data : KeyValue<number,number>[]) {
    this.dataTransmitter.Put(this.apiUrl+'/api/aboutus/sort', data);    
}

and if I debug the following data container then it looks like this:

Datacontainer

I have the following in my .net core Webserver's Controller

[HttpPut("[action]")]
public ActionResult<bool> Sort(IList<KeyValuePair<int, int>> dto)
{
    return Ok(_aboutUsService.Sort(dto));
}

However i get the following error when trying to send it via PUT:

The JSON value could not be converted to System.Collections.Generic.List`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.Int32]]. Path: $[0] | LineNumber: 0 | BytePositionInLine: 8.

Weird thing is that I've already used the same technique in another older version of .net core and there everything seems to work.

I also noticed that since .net core 3.1 the KeyValue in C# changed to KeyValuePair but in older versions of .net core it was KeyValue.

Does that have to do something with my related error?

And how can I serialize the KeyValue from Angular so that my Webserver can read it?


Solution

  • I was able to solve the Issue by creating my own KeyValue Class like so:

    public class KeyValue<K,V>
    {
        public K Key { get; set; }
        public V Value { get; set; }
    }
    

    after this my Controller Method now looks like this:

    [HttpPut("[action]")]
    public ActionResult<bool> Sort([FromBody] IList<KeyValue<int, int>> dto)
    {
        return Ok(_aboutUsService.Sort(dto));
    }
    

    Thanks to this approach the Controller was able to receive the sent Array of KeyValue over PUT from Angular to my Webserver...enter image description here