Create ASP.NET Core Web API Project
On the Visual Studio, create new ASP.NET Core Web API Application project
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
Create Controller
Create new folder named Controllers. In this folder, create new controller named FileController.cs, this file contains Web API upload file to server 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 Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreWebAPIWithRealApps.Controllers
{
[Route("api/file")]
public class FileController : Controller
{
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", file.FileName);
var stream = new FileStream(path, FileMode.Create);
file.CopyToAsync(stream);
return Ok(new { length = file.Length, name = file.FileName });
}
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(FileInfo fileInfo)
{
try
{
var httpClient = new HttpClient();
var multipartFormDataContent = new MultipartFormDataContent();
httpClient.BaseAddress = new Uri(BASE_URL);
var fileContent = new ByteArrayContent(File.ReadAllBytes(fileInfo.FullName));
multipartFormDataContent.Add(fileContent, "file", 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 fileInfo = new FileInfo(@"E:\Photo\thumb2.gif");
var uploadRestClientModel = new UploadRestClientModel();
var result = uploadRestClientModel.Upload(fileInfo).Result;
var fileResult = result.Content.ReadAsAsync<FileResult>().Result;
Console.WriteLine("Status: " + result.StatusCode);
Console.WriteLine("File name: " + fileResult.Name);
Console.WriteLine("File size: " + fileResult.Length);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
Output
Status: OK
File name: thumb2.gif
File size: 8063
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