How to setup a webapi controller for multipart/form-data
By FoxLearn 2/7/2025 4:03:42 AM 641
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"}
The error you're encountering (The request entity's media type 'multipart/form-data' is not supported for this resource
) typically occurs when you're trying to send a multipart/form-data
request to an endpoint that isn't configured to handle this type of data.
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 } ); } }
Ensure that the API endpoint you're calling is designed to handle multipart/form-data
.
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core
- How to Create a custom model validation attribute in ASP.NET Core
- How to disable ModelStateInvalidFilter in ASP.NET Core
- How to fix LoginPath not working in ASP.NET Core
- Synchronous operations are disallowed