Using Google Cloud Storage in ASP.NET Core

Sena Kılıçarslan
.NET Core
Published in
9 min readJan 12, 2020

--

In this post, I will show how to use Google Cloud Storage (GCS) to store and serve images of an ASP.NET Core web application.

The sections of this post will be as follows:

  • About the App
  • Sign up for Google Cloud
  • Google Cloud Storage
  • Modify the App
  • Test the App
  • Clean up the Resources

About the App

The application that we will modify manages a database of TV Shows and its main page looks like below:

The app is an ASP.NET Core MVC web application and it uses EF Core to perform CRUD operations on a SQL Server database. You can download the source code from this Github repository.

If you are interested in the development process of this application, you can check this post.

In the current version, the image of the TV show needs to exist in the wwwroot/images folder of the project and is entered as shown below:

In the modified version, the user will select the image file to be uploaded and the file will be uploaded to Google Cloud Storage in the create action.

Let’s start by performing the necessary actions in the Google Cloud Platform (GCP).

Sign up for Google Cloud

If you don’t have a Google Cloud account, go to Google Cloud web site and click Get started for free button. Sign up with your Gmail account and get $300 (for free) to spend on Google Cloud Platform over the next 12 months.

Google Cloud Storage

In this section, we will do the necessary operations to use Google Cloud Storage service of the GCP for our application.

Cloud Storage provides worldwide, highly durable object storage that scales to exabytes of data. You can access data instantly from any storage class, integrate storage into your applications with a single unified API, and easily optimize price and performance.

Cloud Storage is typically used to store unstructured data.

First, we will create a new GCP project in the Google Cloud Console. (You can use an existing project too). Select the dropdown box shown in the red box and then click New Project.

Give your project a name and then click Create.

Next, we will create a bucket to store our images.

Buckets are the basic containers that hold your data in Cloud Storage.

Write Storage in the search box and then click Storage.

Click Create Bucket on the next screen. Then,

  • give a unique name for your bucket,
  • choose Standard for Storage class,
  • choose a suitable Location for you,
  • click Create.

After the creation is completed, we will see our bucket as follows:

Next, we will make the bucket publicly readable so it can serve files:

  • Select the Permissions tab shown in the red box above.
  • Click the Add members button.
  • In the New members field, enter allUsers.
  • In the Roles drop-down, select the Storage sub-menu, and click the Storage Object Viewer option as shown below:
  • Click Save.

Now, we will set up a service account and download credentials to run our application locally.

Enter APIs & Services in the search box of the cloud console. Then,

  • click Credentials on the left pane,
  • click Create credentials,
  • select Service account key.

In the next dialog, create the new service account as shown below:

After this operation, a new JSON file is created and we download this file to our computer to use in our project in the next section.

Modify the App

In this section, we will perform the modifications listed below in our application so that we will be able to upload the image of the TV show that will be used in the application:

  • Modify the model
  • Modify the views
  • Edit the application settings
  • Install the Google Cloud Storage package
  • Create a new class for GCS operations
  • Edit Startup.cs
  • Modify the controller

Modify the model

Change the TvShow model as seen below:

We added two new properties to the model:

  • ImageFile will be used to get the image file to be uploaded
  • ImageStorageName will be used to keep the name of the object stored in the GCS bucket related to the image file uploaded.
  • MaxFileSize and PermittedExtensions are custom validation attributes used to limit the maximum file size and extensions of the image file. (You can find the related classes in the CustomValidationAttributes folder of the final version of the project which will be shared at the end of the tutorial)

Next, we will run the following commands in the Package Manager Console to update the database.

Add-Migration ImageFile
Update-Database

Modify the views

In the Create.cshtml, add the parts shown in red boxes below and delete the part related to ImageUrl :

Modify the Edit.cshtml as shown below:

Next, we will add style attribute to the ImageUrl to make the height and width of image standard in the other views.

In the Delete.cshtml and Details.cshtml, change the part related to ImageUrl with the following:

<dd class="col-sm-10"><img src="@Url.Content(Model.ImageUrl)" alt="Image" style="width: 150px; height: 220px;"/></dd>

In the Index.cshtml, change the part related to ImageUrl with the following:

@if (item.ImageUrl != null){<img src="@Url.Content(item.ImageUrl)" alt="Image" style="width: 150px; height: 220px;"/>}

Edit the application settings

Add the following key-value pairs to appsettings.json and change the values with the values of the credential file path and GCS bucket that you created in the previous section:

Install the Google Cloud Storage package

Right-click on the project and select Manage Nuget Packages… and then install the following package:

Create a new class for GCS operations

Now, we will create a new class that will manage the file upload and delete operations in our GCS bucket using the client library that we installed above.

Right-click on the project and create a new folder called CloudStorage. Then add the following ICloudStorage interface to this folder.

Next, add a class called GoogleCloudStorage which implements the ICloudStorage under this folder:

This class gets the credential JSON file name and the GCS bucket name from the application settings that we defined previously.

As seen in the implementation, it has two methods:

  • UploadFileAsync: Uploads the file given with the parameter imageFile to the GCS with the given fileNameForStorage as object name.
  • DeleteFileAsync: Deletes the file with the given fileNameForStorage as object name from the GCS bucket.

We will use these methods in the Create, Edit and Delete action methods of the TvShowsController.

Edit Startup.cs

Before using the GoogleCloudStorage class in the TvShowsController, we need to register it as a service in Startup.cs to the built-in IoC container as it will be injected to the controller via constructor injection.

Add the following line to the end of the ConfigureServices method:

services.AddSingleton<ICloudStorage, GoogleCloudStorage>();

Modify the controller

Now, we will modify Create, Edit and Delete action methods of the TvShowsController.

First, change the following part for the dependency injection:

Second, add the following new methods to the controller class:

FormFileName method creates a new object name in the format below:

{tv-show-title}-{current-datetime}.{file-extension}

Then, this new name is passed as a parameter to the UploadFile method and it is used as the object name in the GCS bucket. This object name will also be stored in the TvShow.ImageStorageName field and will be used to delete the object from the GCS bucket if needed.

UploadFile method calls the UploadFileAsync method that we defined in the GoogleCloudStorage class previously. Notice that after the file is uploaded to GCS, the public URL to this file is returned and we will use this URL to serve the file directly from GCS. So we store this value in the TvShow.ImageUrl field to show the poster in the views of the application.

Next, change the Create method as shown below:

As seen above, when we create a new TV Show, we also upload the image file (if the user chooses one) to the GCS using the UploadFile method.

Next, change Edit method as shown in the below image:

In the Edit method, we first check if there is a related poster for this TV Show and if it exists we delete that from the GCS. Then, we upload the new image to the GCS.

Lastly, add the following code to the DeleteConfirmed method:

You can find the last version of the project in this GitHub repository.

Test the App

Now, we will test the application and see if everything works as expected.

First, let’s create a new TV Show:

As you see above, we can now choose the image file from our computer. After clicking the Create button, the new record including the fields related to the image is created in the database as shown below:

We can also check that the object is created in our bucket in the GCS:

Notice that the ImageStorageName in the table and the Name field in the GCS bucket match.

In the Index view of the application, the poster of the image is served from the GCS using the ImageUrl field in the table.

Next, we will test the Delete view:

After clicking the Delete button, if we refresh the GCS bucket we see that the image object is deleted here as well.

You can check the Edit view and see that everything works as expected.

Clean up the Resources

To avoid incurring charges, we can delete our GCP project to stop billing for all the resources used within the project.

In the Google Cloud Console, search for Manage Resources. In this menu, select your project and click Delete.

That’s the end of the post. I hope you found this post helpful and easy to follow. If you have any questions and/or comments, please let me know in the responses section below.

And if you liked this post, please clap your hands 👏👏👏

Bye!

References

https://cloud.google.com/storage/

https://cloud.google.com/storage/docs/quickstart-console

https://cloud.google.com/appengine/docs/flexible/dotnet/using-cloud-storage

--

--

Sena Kılıçarslan
.NET Core

A software developer who loves learning new things and sharing these..