I’m trying to upload a file using swagger/postman using .net framework
The issue that I’m facing is that in .NET Core you can simply just use IFormFile within your Model class and you’re basically all set
But now that I’m not using .NET Core, I’m lost
The goal is to make a POST request that contains a String and File
public class UploadDoc
{
public string Desc { get; set; }
public HttpRequest File { get; set; }//I've tried different things here
}
And here is the post
public async Task<IHttpActionResult> Post(UploadDoc uploadDoc)
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var buffer = await file.ReadAsByteArrayAsync();
File.WriteAllBytes(@"abcdef.pdf", buffer);
}
return Ok();
}
Edit: Adding more clarification — my goal is to create an API Post call and ultimately, all I want is to take 2 inputs from the user
- Input 1: A string
- Input 2: A PDF File
So the postman request should look like this
When using .NET Core 6, I could do this simply by creating a model class that had
public string Desc { get; set; }
public IFormFile? formFile { get; set; }
And then setting up my API Call like so:
[HttpPost]
public async Task<IActionResult> Post([FromForm] DummyModel dummyModel)
{
var uploadedDocument = await FileHelper.UploadImage(dummyModel.formFile); // this dummyModel.formFile would contain what was uploaded by the user
}
Now I’m trying to figure out how to do something similar within .NET Framework Web API
Edit 2:
I think I need to use the multipartformdata thing but my issue is I want my end-user to always only send me 2 things
A string and a PDF File
2
Answers
Not sure I fully understand your question, but to post in .NET you could:
see:
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.postasync?view=net-6.0#system-net-http-httpclient-postasync(system-uri-system-net-http-httpcontent)
and:
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent?view=net-6.0