2

I am trying pass an object which consists of different data type. I am always getting null value for orderDetails in Web API.

However if do this,

purchaseOrder.Attachments = null, 

in the client then orderDetails is no longer null and I have other informations like "SendEmail" and PurchaseOrderNumber.

It looks I might not be correctly set the parameter in the client (angular 2).

However testing the same Web Api method from Console app works fine and I am not getting a null value.

Do I need to separate the JSON data and byte array?

regards, -Alan-

Models

public class Attachments
{
   public int AttachmentId { get; set; }
   public string FileName { get; set ;}
   public byte[] FileData { get; set ;}
}
public class UpdatePurchaseOrderViewModel
{
      public bool SendEmail { get; set; }
      public int PurchaseOrderNumber { get; set; }
      public Attachments Attachments { get; set;
}

Here is my Web API put method definition

[HttpPut("AddPurchaseOrderNumber/{purchaseOrderId}")]
       public StatusCodeResult AddPurchaseOrderNumber(int purchaseOrderId, [FromBody] UpdatePurchaseOrderViewModel orderDetails)
       {
           try
           {
               var status = _service.AddPurchaseOrderNumber(purchaseOrderId, orderDetails);
               if (status == 200)
                   _unitOfWorkAsync.SaveChanges();
               else return StatusCode(status);//No Data
           }
           catch
           {
               return StatusCode(400); // Bad Request
           }
           return StatusCode(200);//OK
       }

Typescript snippet

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept','application/json');

let options = new RequestOptions({ headers: headers });
var body = JSON.stringify(
                purchaseOrder
            );

var uri = 'http://localhost:33907/api/purchaseorder/addpurchaseordernumber/' + purchaseOrderId;

     return this._http.put(uri, body , options)
            .map((response: Response) => {
             let data = response.json();
             if (data) {
                        return true;
                    }
                    else {
                        return false;
                    }
                })

Update

The orderDetails is created as below

  let file = Observable.create((observer) => {
            let fr = new FileReader();
            let data = new Blob([this.attachment]);
            fr.readAsArrayBuffer(data);
            fr.onloadend = () => {
                observer.next(fr.result);
                observer.complete();
            };
            fr.onerror = (err) => {
                observer.error(err);
            }
            fr.onabort = () => {
                observer.error("aborted");
            }
        });
        file.map((fileData) => {
            //build the attachment object which will be sent to Web API
            let attachment: Attachments = {
                AttachmentId: '0',
                FileName: this.form.controls["attachmentName"].value,
                FileData: fileData
            }
            //build the purchase order object
            let order: UpdatePurchaseOrder = {
                SendEmail: true,
                PurchaseOrderNumber:this.form.controls["purchaseOrderNumber"].value * 1, //for casting purpose
                Attachments: attachment
            }
            console.log("Loading completed");
            return order;
        })

1 Answer 1

1

When sending objects that have byte arrays as a property back and forth between a client to a WebAPI endpoint, I typically use a DTO that stores the property to explicitly define it as a Base64 string. On the server side I map the DTO to my entity by converting the Base64 string to / from the byte array for server side operations and storing in the database.

The serializer will do something like this automatically but the format passed from JavaScript may not match what the WebAPI JSON serializer is expecting (which is why it's working from your C# Console App).

You didn't include how you are creating the purchaseOrder object in your JavaScript so I can't comment on how that object is being setup - which may be where your issue is.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.