Reputation: 3937
I am using postman to test my .net core API, when i am trying to post data via postman form-data this returns a 415 even if i set the Content-Type header to application/json as the common solution for this issue appears to be online. If i fire the request without any files via the raw postman option and set the content type as JSON(application/json) this request reaches the API successfully.
Here is how my API looks:
[HttpPost("{organization}")]
public IActionResult Post([FromBody] Asset asset, string organization)
{
//Api body
//Get files from request
Task uploadBlob = BlobFunctions.UploadBlobAsync(_blobContainer,Request.Form.Files[0]);
}
And here is how the failed postman request looks like
and the header for that request
What else am i missing for this to work?
Small update
This works fine if i remove [FromBody]Asset asset
and just pass the file
Upvotes: 2
Views: 4208
Reputation: 3937
Turns out that for some weird reason I was not allowed to pass any of them as a variable of my controller but it works if I retrieve both from the Request
.
if (!Request.Form.ContainsKey("asset"))
{
return BadRequest("Asset cannot be empty");
}
Asset asset = JsonConvert.DeserializeObject<Asset>(Request.Form.First(a => a.Key == "asset").Value);
and for the file
var file = equest.Form.Files[0]
Not sure why this is the case and would appreciate if someone could explain this to me but this seems to solve my issue.
Upvotes: 0
Reputation: 557
Try using the [FromForm] attribute instead of the [FromBody] attribute:
[HttpPost("{organization}")]
public IActionResult Post([FromForm] string asset, string organization, IFormFile fileToPost)
{
//Api body
Asset asset = JsonConvert.DeserializeObject<Asset>(asset);
//Get files from request
Task uploadBlob = BlobFunctions.UploadBlobAsync(_blobContainer, fileToPost);
}
I can't say for sure, but my guess is that in postman, since you're making a form-data request, your content-type would end up being "multipart/form-data" (if you debug the request when it is being processed, you can see that the content type changes to multipart even though you set it to application/json).
But in your Controller's POST action you specify that you expect an Asset object from the body (which expects a JSON object by default). So you get a 415 since your request's content type is multipart while your API expects application/json because you used the [FromBody] attribute.
Upvotes: 4