I'm using VS2015 to create a WebApi project. Specifically, I'm trying to write a simple web service to upload files using POST.
I have done this before using previous versions of Visual Studio, but VS2015 utilizes ASP.NET 5 and MVC 6 which apparently has some major api changes.
Before, I could use something like this:
Request.Content.ReadAsMultipartAsync().Result.Contents
BTW, this is what every site I googled recommends. But my copy of VS2015 gives me the following compile time error message:
'HttpContent does not contain a definition for ReadAsMultipartAsync'
The overall project structure for WebApi's seem to be revamped in VS2015. At this point I have no idea what's wrong (whether it's a code issue or a VS2015 issue). I've spent the last couple of days trying to get this resolved. Can anyone provide insight as to what I'm doing wrong?
Below is my controller in it's entirety:
[Route("api/[controller]")]
public class UploadController : Controller
{
private readonly IApplicationEnvironment appEnvironment;
public UploadController(IApplicationEnvironment appEnvironment)
{
this.appEnvironment = appEnvironment;
}
// POST api/values
[HttpPost]
public void Post(HttpRequestMessage request)
{
string logFolder = "logs";
string fileName = "uploader.log";
string logFile = Path.Combine(this.appEnvironment.ApplicationBasePath, logFolder, fileName);
string directory = Path.GetDirectoryName(logFile);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (Stream requestStream = GetStreamFromUploadedFile(request))
{
using (Stream fileStream = System.IO.File.Create(logFile))
{
try
{
requestStream.CopyTo(fileStream);
}
finally
{
// No longer supported?
//fileStream.Close();
//requestStream.Close();
}
}
}
}
private static Stream GetStreamFromUploadedFile(HttpRequestMessage request)
{
IEnumerable<HttpContent> parts = null;
Task.Factory
.StartNew(() => parts = request.Content.ReadAsMultipartAsync().Result.Contents,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default)
.Wait();
Stream stream = null;
Task.Factory
.StartNew(() => stream = parts.First().ReadAsStreamAsync().Result,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default)
.Wait();
return stream;
}
}