Create ASP.NET Core Web API Project
On the Visual Studio, create new ASP.NET Core Web API Application project
Select Empty Template
Click Ok button to Finish
Add Configurations
Open Startup.cs file and add new configurations as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace LearnASPNETCoreWebAPIWithRealApps
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc();
}
}
}
Add Image Folder
Create new folder named images in wwwroot folder
Entities Class
Create Models folder. In this folder, create new class named FileUploadResult.cs as below:
FileUploadResult Entity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LearnASPNETCoreWebAPIWithRealApps.Models
{
public class FileUploadResult
{
public long Length { get; set; }
public string Name { get; set; }
}
}
Create Controller
Create new folder named Controllers. In this folder, create new controller named FileController.cs, this file contains Web API as below:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using LearnASPNETCoreWebAPIWithRealApps.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreWebAPIWithRealApps.Controllers
{
[Route("api/file")]
public class FileController : Controller
{
[HttpPost("upload")]
public async Task<IActionResult> Upload(List<IFormFile> files)
{
try
{
var result = new List<FileUploadResult>();
foreach (var file in files)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", file.FileName);
var stream = new FileStream(path, FileMode.Create);
file.CopyToAsync(stream);
result.Add(new FileUploadResult() { Name = file.FileName, Length = file.Length });
}
return Ok(result);
}
catch
{
return BadRequest();
}
}
}
}
Structure of ASP.NET Core Web API Project
Consume Web API from Console Application
Create Console App (.NET Framework) Project in Visual Studio.
Entity Class
Create Models folder in Console Application. In this folder, create new class named FileResult.cs as below:
FileResult Entity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnASPNETCoreWebAPIWithRealApps_Client
{
public class FileResult
{
public long Length { get; set; }
public string Name { get; set; }
}
}
Create UploadRestClientModel
UploadRestClientModel class contain methods call Web API. Add reference to System.Net.Http.Formatting library from Nuget Packages
using LearnASPNETCoreWebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace LearnASPNETCoreWebAPIWithRealApps_Client
{
public class UploadRestClientModel
{
private string BASE_URL = "http://localhost:18942/api/file/";
public Task<HttpResponseMessage> Upload(List<FileInfo> fileInfos)
{
try
{
var httpClient = new HttpClient();
var multipartFormDataContent = new MultipartFormDataContent();
httpClient.BaseAddress = new Uri(BASE_URL);
foreach (var fileInfo in fileInfos)
{
var fileContent = new ByteArrayContent(File.ReadAllBytes(fileInfo.FullName));
multipartFormDataContent.Add(fileContent, "files", fileInfo.Name);
}
return httpClient.PostAsync("upload", multipartFormDataContent);
}
catch
{
return null;
}
}
}
}
Run Console Application
using LearnASPNETCoreWebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace LearnASPNETCoreWebAPIWithRealApps_Client
{
class Program
{
static void Main(string[] args)
{
try
{
var fileInfos = new List<FileInfo>() {
new FileInfo(@"E:\Photo\thumb1.gif"),
new FileInfo(@"E:\Photo\thumb2.gif"),
new FileInfo(@"E:\Photo\thumb3.gif")
};
var uploadRestClientModel = new UploadRestClientModel();
var result = uploadRestClientModel.Upload(fileInfos).Result;
var fileResults = result.Content.ReadAsAsync<List<FileResult>>().Result;
Console.WriteLine("Status: " + result.StatusCode);
foreach (var fileResult in fileResults)
{
Console.WriteLine("File name: " + fileResult.Name);
Console.WriteLine("File size: " + fileResult.Length);
Console.WriteLine("====================");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
Output
Status: OK
File name: thumb1.gif
File size: 5095
====================
File name: thumb2.gif
File size: 8063
====================
File name: thumb3.gif
File size: 8192
====================
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- Modern API Design with ASP.NET Core 2: Building Cross-Platform Back-End Systems
- Mastering ASP.NET Web API: Build powerful HTTP services and make the most of the ASP.NET Core Web API platform
- .NET Core in Action