I see lots of examples of WebAPIs accepting files. However, I have yet to find a solution as to why, no matter what I've tried, to get my HttpContext.Current.Request.Files to ever have a file in it that I am posting to the Web API through Postman. (I have also posted that image through a Console Application and got the same result)
[HttpPost]
[ActionName("Post")]
[ResponseType(typeof(PeliquinApiRsp))]
public IHttpActionResult Post(int personId)
{
var empPicture = PeliquinIOC.Resolve<IEmpPictureBL>(UserId, UserName, PropertyCode);
if (!(IsAllowed(SysPrivConstants.SYSPRIV__TYPE_PERSONNEL, SysPrivConstants.SYSPRIV__FUNC_PERSONNEL_CARDHOLDER, SysPrivConstants.SYSPRIV__LEVEL_FULL)))
return (Unauthorized());
var apiRsp = new PeliquinApiRsp();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count == 0)
return BadRequest();
empPicture.Post(httpRequest.Files[0].InputStream, personId);
apiRsp.SetStatus();
apiRsp.SetData("EmpPicture");
return (Ok(apiRsp));
}
It is a very simple method. I've been using Postman to post a Binary .jpg file. I have set the content-type = "multipart/form-data". No error is throw in my code, other than the .Files = 0.
I have some additional settings in my WebApiConfig for the rest of the API, but I'll include them just in case, along with the route for this particular method:
config.Formatters.Remove( config.Formatters.XmlFormatter );
config.Formatters.JsonFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue( "application/json" ) );
config.Formatters.FormUrlEncodedFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
config.Routes.MapHttpRoute(
name: "EmpPicturePost",
routeTemplate: "api/EmpPicture/{personId}",
defaults: new { controller = "EmpPicture", action = "Post" },
constraints: new { personId = @"^\d+$", httpMethod = new HttpMethodConstraint(HttpMethod.Post, HttpMethod.Options) }
);
I am at wit's end trying to figure out why something so simple, just doesn't work. I've tried quite a few other way of doing this, that were all more MVC-like, but this isn't an MVC app, and they threw different errors. Thanks for any help.