Returning binary file from controller in ASP.NET Web API

后端 未结 8 802
离开以前
离开以前 2020-11-22 02:55

I\'m working on a web service using ASP.NET MVC\'s new WebAPI that will serve up binary files, mostly .cab and .exe files.

The following co

8条回答
  •  一生所求
    2020-11-22 03:46

    While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :

    • In the request, set header "Accept: application/octet-stream".
    • Server-side, add a media type formatter to support this mime type.

    Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).

    You can add this formatter into your global config :

    HttpConfiguration config;
    // ...
    config.Formatters.Add(new BinaryMediaTypeFormatter(false));
    

    WebApi should now use BinaryMediaTypeFormatter if the request specifies the correct Accept header.

    I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").

提交回复
热议问题