Search code examples
c#asp.net-web-api2postmanasp.net-web-api-routing

The requested resource does not support http method 'POST' when sending multipart-form data


I have a controller like below:

[RoutePrefix("api/File")]
public class FileController : ApiController
{
        [HttpPost]
        [Route("Add")]        
        public async Task<HttpResponseMessage> AddFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
            var provider = new MultipartFormDataStreamProvider(root);
            var result = await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    if (key == "companyName")
                    {
                        var companyName = val;
                    }
                }
            }


            //Do whatever you want to do with your file here

            return this.Request.CreateResponse(HttpStatusCode.OK, "OK");
        }
}

If i do a post request in postman like in picture: enter image description here

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.MapHttpAttributeRoutes();

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        //config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
        config.Formatters.Add(new BrowserJsonFormatter());
    }
}

The function does not get hit
Any idea what I am doing wrong?


Solution

  • Try changing the order in which you register the attribute routes:

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

    Also if you always use attribute based routing I would recommend you removing the default route registration.