Skip to content

Web API

txgz999 edited this page Jun 2, 2020 · 8 revisions

We discuss ASP.NET Web API, mainly in the context of serving as service to Angular client.

Send Binary Data

When we return a .Net object or collection of objects in a method of ApiController, Web API would automatically serialize the object and return the content in either xml format or json format, depends the Accept value in the request header. When the Angular HttpClient object sends a request, by default, it’s Accept header contains application/json, thus the response would be in json format.

Accept: application/json, text/plain, */*

That being said, Web API is also capable to send binary data. First at the server side, we will return a HttpResponseMessage object

public HttpResponseMrssage Get(int I’d) {
   var result = new HttpResponseMessage(HttpStatusCode.Ok);
   byte[] data = ...
   result.Content = new ByteArrayContent(data);
   result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
   result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
       FileName = "myfile.pdf"
   };
   return result;
}

then at the client side, we need to add to the following to the get method call

this.http.get(url, data, { responseType: 'blob' }) 

Notice this change does not alter the Accept header value, since that value is okay for any data. It would change the way Angular parse the response data. If we don’t set it, we would get a HttpErrorResponse error complaining syntax error when parsingthe. Response as json data.

If we need to inspect response header values, we need to modify the call a little bit as following:

Clone this wiki locally