How to setup a webapi controller for multipart/form-data
By FoxLearn 2/16/2024 7:42:48 AM 304
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 } ); } }
- How to use CORS in ASP.NET Core
- How to Send Emails in ASP.NET Core
- How to Run Background Tasks in ASP.NET Core with Hosted Services
- Implementing Scheduled Background Tasks in ASP.NET Core with IHostedService
- Creating an Web API in ASP.NET Core
- 8 Essential Tips to Protect Your ASP.NET Core Application from Cyber Threats
- 10 Common Mistakes ASP.NET Developers Should Avoid
- How to Upload Files Using C# ASP.NET FileUpload Control