'Multipart form doesn't receive fields
I'm trying to get a file and model to my api controller and test it by sending request from fiddler. So far I have managed to receive a file using MultipartDataMediaFormatter but I can't receive fields. The some variable will be empty:
[HttpPost]
public IHttpActionResult Add(FormData formData)
{
HttpFile file;
formData.TryGetValue("fieldNameHere", out file);
string some;
formData.TryGetValue("code", out some);
The request is
---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="result.pdf"
Content-Type: application/pdf
<@INCLUDE *C:\Users\mikhail.yakhyaev\Documents\result.pdf*@>
---------------------------acebdf13572468
Content-Disposition: form-data; name="code"
asdf
---------------------------acebdf13572468--
I've tried to make signature as IHttpActionResult Add(HttpPostedFileBase fieldNameHere)
but the error is returned that request didn't hit the method.
Maybe the request itself contains error?
Solution 1:[1]
I just meet the same problem, Luckily tried a lot and found out the solution. Did you notice that the request of your model content-type is also form-data, that's the reason you cannot use FormData in api in that way.The code :
public IHttpActionResult Add(FormData formData)
{
foreach(var fileValue in formData.Files){
//do any you want
}
foreach(var field in formData.Fields){
//do any you want
}
//may that be helpful
}
Solution 2:[2]
Did you add encType = "multipart/form-data"
to your form tag in view?
Solution 3:[3]
success case
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri(baseAddress);
foreach (var item in paramData)
{
content.Add(new StringContent(item.Value), item.Key);
}
......
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Conan Lee |
Solution 2 | sam |
Solution 3 | JPomichael |