The possibilities with the Fuga Object Store are endless. One of the scenarios is connecting your .NET Core application to the Fuga Object Store, this way you can access for example files on your Object Store! In this tutorial, we will teach you how to make a simple .NET Core MVC file upload application that uses the Fuga Object Store.
Requirements
API keys
To connect to your Fuga Object Store access and secret keys are required. If you already have these you can skip this chapter.
-
To list and create API keys for the Object Store we need the Fuga OpenStack CLI. If you haven’t installed it yet check out our tutorial.
-
After following the tutorial for your operating system it’s time to list the credentials. We need the credentials to access our Object Store container in later steps.
-
To list all the credentials, enter the command:
openstack ec2 credentials list
-
If the list of credentials is empty, a new pair of credentials can be generated with:
openstack ec2 credentials create
-
Either copy the Access and Secret key to the clipboard or save them temporarily.
Creating a Fuga Object Store container
-
Open your Fuga Dashboard and open the ‘Object Store’ section.
-
Click on ‘Containers’ and create a new container.
We now have a container that is ready to be used in the upcoming steps.
Creating a new .NET Core project
In this chapter, we will be creating a .NET core project using a template with MVC.
-
Create a new folder for the .NET Core project:
mkdir fugadotnet
-
Open the folder in your terminal with the following command:
cd fugadotnet
-
Create a new empty .NET Core ASP project by executing the following command:
dotnet new web
An empty web project will be in your fugadotnet directory.
-
Create a new folder inside your fugadotnet folder called Controllers:
mkdir Controllers
-
Create a new folder inside your fugadotnet folder called Views:
mkdir Views
-
Go inside the Views folder with the following command:
cd Views
-
Inside the Views folder, create a new folder called ObjectStore.
Enter the following command:
mkdir ObjectStore
This is the name of the controller that we will create in the next chapter, feel free to change this.
-
Open this project in your favorite IDE or text editor, for example, Visual Code or Atom.
Adding the AWS .NET S3 SDK to your project
The Fuga Object Store is Amazon S3 compatible, that’s why we can use the official Amazon SDK. In this chapter, we will be installing the AWS S3 SDK package to our .NET Core project.
-
In your terminal execute the following command in your project root:
dotnet add package AWSSDK.S3 --version 3.3.18.3
Creating a new Controller
In this chapter we will be creating a Controller, this will contain most of the logic for the Object Store.
-
Inside your Controllers folder, create a new file called ObjectStoreController.cs within your text editor or with the following command:
touch ObjectStoreController.cs
-
Open the ObjectStoreController.cs with your text editor and paste in the following code:
using System;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Amazon.S3;
using Amazon.S3.Model;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace fugadotnet.Controllers
{
public class ObjectStoreController : Controller
{
private string container = "YOUR_CONTAINER_NAME_HERE";
private AmazonS3Client fuga = Startup.GetS3Client();
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string name)
{
if (HttpContext.Request.Form.Files != null)
{
var files = HttpContext.Request.Form.Files;
foreach (var file in files)
{
Console.WriteLine(file.FileName);
if (file.Length > 0)
{
UploadObjectToObjectStore(file);
}
}
}
return View();
}
public IActionResult Get([FromQuery(Name = "name")] string name)
{
ViewData["content"] = GetObject(name).Result;
return View();
}
async Task<string> GetObject(string name)
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = container,
Key = name
};
using (GetObjectResponse response = await fuga.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
async Task UploadObjectToObjectStore(IFormFile file)
{
var result = string.Empty;
using (var reader = new StreamReader(file.OpenReadStream()))
{
result = reader.ReadToEnd();
}
var request = new PutObjectRequest
{
BucketName = container,
Key = file.FileName,
ContentBody = result
};
await fuga.PutObjectAsync(request);
}
}
} -
Inside your ObjectStoreController.cs, edit the container variable to your container name.
-
Save the file.
Creating the views
-
Inside your fugadotnet/Views/ObjectStore folder, create two views with the following command:
touch Index.cshtml Get.cshtml
-
Open Index.cshtml with your text editor and paste in the following:
<h1>Fuga Object Store file upload</h1>
<form method="post" enctype="multipart/form-data" asp-controller="ObjectStore" asp-action="Index">
<div class="form-group">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
</form> -
Save the file.
-
Open Get.cshtml and paste in the following:
<b>@ViewData["content"]</b>
-
Save the file.
Attaching our controller to the project and initializing the connection
Before
-
Open the Startup.cs file located in the project root and paste in the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Runtime;
using Amazon.S3;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace fugadotnet
{
public class Startup
{
private static AmazonS3Client client;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "http://object.api.fuga.cloud";
config.ForcePathStyle = true;
config.SignatureVersion = "2";
BasicAWSCredentials cred = new BasicAWSCredentials($"{Configuration["AccessKey"]}",
$"{Configuration["SecretKey"]}");
client = new AmazonS3Client(cred, config);
}
public static AmazonS3Client GetS3Client()
{
return client;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=ObjectStore}/{action=Index}/{id?}");
});
}
}
} -
Save the file.
Configuring access to your Fuga Object Store container
-
In your project root, create a new file called appsettings.json:
touch appsettings.json
-
Copy paste in the following settings:
{
"AccessKey": "YOUR_ACCESS_KEY",
"SecretKey": "YOUR_SECRET_KEY"
} -
Replace the YOUR_ACCESS_KEY and YOUR_SECRET_KEY with the keys from the API keys chapter.
-
Save the file.
Testing the application
-
Run the application by executing the following command inside your project root folder:
dotnet run
Your web browser will show you a file upload page.
-
Upload a text file, for example, test.txt with Hello, World as content.
-
Browse to https://localhost:5001/ObjectStore/Get?name=test.txt
Hello, World will be displayed.