Mapping datatype to Angular.

Abhijit Shrikhande 337 Reputation points
2022-01-14T15:36:05.99+00:00

I have a model in my web API class.

public class InspectionPhoto
    {
        public int Id { get; set; }
        public int InspectionId { get; set; }
        public int CategoryId { get; set;}
        public string Employee { get; set; } = "DUMMYEMP";
        public byte[] Data { get; set; }    
    }

I am building a corresponding model in my Angular client app.

export class InspectionPhoto
{
    public Id: number;
    public InspectionId: number;
    public CategoryId: number;
    public Employee: string;
    public Data: Blob;
}    

Angular code to call the service. This is currently hard-coded for testing.

public callwebapi(event)
  {
    console.log('welcome to callwebapifunction');
      console.log(event);
      //var jsonIn = document.getElementById("mytext").innerText;
      var jsonIn = '{"Id": -1,   "InspectionId": 95,   "CategoryId": 9,   "Employee": "Golly Goblin", "Data":"iVBORw0KGgoAAAANSUhEUgAAASwAAABkCAIAAACzY5qXAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAAR5JREFUeF7t0zEBAAAMw6D5N93JyAMeuAEpCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhJiEEJMQYhJCTEKISQgxCSEmIcQkhNT26WBE8+9D0NEAAAAASUVORK5CYII"}'; 
      console.log(jsonIn);
      const uri = 'https://localhost:44304/api/values';
      let header = new HttpHeaders();
      header.set('Access-Control-Allow-Origin','*');
      header.append('Content-Type', 'application/json;charset=UTF-8');
      header.append('accept', 'application/json');

      try{
        console.log('trying httpPost');
      this.http.post<InspectionPhoto>(uri, jsonIn, {headers: header}).subscribe();
      }catch{
        console.log('i am in catch block');
      }
  }

I am getting this exception thrown:

Exception thrown: 'System.FormatException' in mscorlib.dll
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll

What data type will actually map to a byte array? Is it blob or Image? I am not able to get either to work correctly.
The api works as soon as I drop the Data from both models, but my requirement is to send an image.

Thanks You!

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
326 questions
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 63,501 Reputation points
    2022-01-14T18:15:47.433+00:00

    typically you pass a byte[] as a base64 encoded string. Newtonsoft decode of byte[] expects base64.

    I don't use angular or TypeScript, but in javascript a Blob is a binary data accessible as a file stream, and not supported by JSON.stringify(). you should convert the Blob to a base64 string and pass it as a string from javascript just as in your test code.

    as reading a Blob is async, here is a reader that returns a promise.

    const blobToBase64 = blob => {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      return new Promise(resolve => {
        reader.onloadend = () => {
          resolve(reader.result);
        };
      });
    };
    
    0 comments No comments

  2. Abhijit Shrikhande 337 Reputation points
    2022-01-18T15:22:34.187+00:00

    I don't have a solution for the angular project yet. I was able to resolve this using javascript. Not a very elegant solution, but it works.

    function takepicture() {
                var context = canvas.getContext('2d');
                if (width && height) {
                    canvas.width = width;
                    canvas.height = height;
                    context.drawImage(video, 0, 0, width, height);
                    var data = canvas.toDataURL('image/png');
                    photo.setAttribute('src', data);
                    console.log(data);
                    console.log('+++++++++++++++++++JUST NOT DATA++++++++++++++');
                    var dataPart = data.split(',')[1];
                    console.log('+++++++++++++++++++JUST DATA++++++++++++++');
                    console.log(dataPart);
                    console.log('+++++++++++++++++++JUST DATA++++++++++++++');
                    class nemo {
                        constructor(Id, InspectionId, CategoryId, Employee, Data) {
                            this.Id = -1;
                            this.InspectionId = 95;
                            this.CategoryId = 8;
                            this.Employee = 'Brain Power';
                            this.Data = dataPart;
                        }
                    }
                    const instanceofnemo = new nemo();
                    callwebapi(instanceofnemo);
                } else {
                    clearphoto();
                }
            }
    
            function callwebapi(someclass)
            {
                console.log(JSON.stringify(someclass));
                const uri = 'https://localhost:44304/api/values';
                fetch(uri, {
                    method: 'POST',
                    mode:'no-cors',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(someclass)
                })
                    .then(response => response.json())
                    .catch(error => console.error('Some Failure Occurred.', error));
            }
    
    0 comments No comments

  3. Bruce (SqlWork.com) 63,501 Reputation points
    2022-01-18T23:29:07.287+00:00

    a canvas is a common way to convert binary image to data url where you can extract the base64. in you question you did not identify where the binary data came from or format (though the sample literal was a png).
    .
    this code

                   class nemo {
                         constructor(Id, InspectionId, CategoryId, Employee, Data) {
                             this.Id = -1;
                             this.InspectionId = 95;
                             this.CategoryId = 8;
                             this.Employee = 'Brain Power';
                             this.Data = dataPart;
                         }
                     }
                     const instanceofnemo = new nemo();
                     callwebapi(instanceofnemo);
    

    could be simplified to:

                     callwebapi({
                             Id = -1;
                             InspectionId = 95;
                             CategoryId = 8;
                             Employee = 'Brain Power';
                             Data = dataPart;
                      });
    
    0 comments No comments

  4. konanki 0 Reputation points
    2023-07-11T21:06:18.4466667+00:00

    C#.net byte[] array equal to ArrayBuffer in angular typescript

    C#.net

    public byte[] DocContent { get; set; }

    Angular typescript: DocContent:ArrayBuffer;

    you need to convert Doccontent as base64ToArrayBuffer

     base64ToArrayBuffer(base64: any): ArrayBuffer {
        var binary_string = window.atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++) {
          bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
      }
    
    var content= this.base64ToArrayBuffer(response.DocContent);
            var blob = new Blob([content], { type: response.ContentType });
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.