How to setup a webapi controller for multipart/form-data

By FoxLearn 2/16/2024 7:42:48 AM   304
If you uploaded file through webapi in angularjs and encountered the following error: ExceptionMessage=No MediaTypeFormatter is available to read an object of type ‘HttpPostedFileBase’ from content with media type 'multipart/form-data'.

415 (Unsupported Media Type)

angular.js:15018 Possibly unhandled rejection: {"data":{"Message":"The request entity's media type 'multipart/form-data' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'HttpPostedFileBase' from content with media type 'multipart/form-data'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":"   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"},"status":415,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api/InvoiceTemplate/Upload","data":{"file":{}},"_isDigested":true,"_chunkSize":null,"headers":{"Accept":"application/json, text/plain, */*"},"_deferred":{"promise":{}}},"statusText":"Unsupported Media Type","xhrStatus":"complete"}

To fix the problem you should add a config to WebApiConfig as the following.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}