Upload files to Asp.NET MVC 4-Web API-Http PUT method
So, I have to make a method in my controller for an API that accepts 2 files via PUT (1 json and 1 xml for Data Processing, not for saving the files), and I have to send the request by fiddler.. My request in fiddler is as follows (put Method):
Content-Type: multipart/form-data
Authorization: XXXXX
Host: XXXX
Request Body:
<@INCLUDE *C:\Users\ZZZZ.json*@>
<@INCLUDE *C:\Users\XXXX.xml*@>
Here is my controller code so far (not working)
[HttpPut, Route("api/Student/{studentId}/Classes/{classId}")]
public async Task<string> Put(int studentId, int classId)
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
Stream fileContent = await this.Request.Content.ReadAsStreamAsync();
MediaTypeHeaderValue contentTypeHeader = this.Request.Content.Headers.ContentType;
if (fileContent != null)
return "ok";
return "not ok";
}
So far the file is not uploading ne, it appears in the variable "Request". I also don't have the request property.File. I also tried HttpContext and also had nothing.
I tried the exact same thing but with the POST method (it adds boundaries automatically in the fiddler request, and then I can see the filenames in my controller, but I can't read any of them...
What would they do to make this work? I even have to have one object in json and another in xml... Files have a dynamic structure, i.e. it is not worth creating a specific object for them.
PS: how would they then read the same files without saving them to disk first?
1 answers
If I understood correctly, do you want to receive in the controller the files without needing a model for each type (xml, json) ?
Ever tried using dynamic type in controller parameters ?
public async Task<string> Put(dynamic student, dynamic class)
{
//Logica...
}
Ref.: Using dynamic Type: https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/types/using-type-dynamic