Using Cloud Storage

You can use Cloud Storage to store and serve files, such as movies or images or other static content.

This document describes how to use the Google Cloud Client Library in a flexible environment app to store data in and retrieve data from Cloud Storage.

Before you begin

  • Follow the instructions in "Hello, World!" for .NET on App Engine to set up your environment and project, and to understand how .NET apps are structured in App Engine. Write down and save your project ID, because you will need it to run the sample application described in this document.

  • Make sure you create a Cloud Storage bucket for your application by invoking the following command:

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • Make the bucket publically readable so it can serve files:

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    
  • To run your application locally, set up a service account and download credentials:

    1. Open the list of credentials in the Google Cloud Platform Console.

      Open the list of credentials

    2. Click Create credentials.

    3. Select Service account key.

      A Create service account key window opens.

    4. Click the drop-down box below Service account, then click Compute Engine default service account.

    5. Select JSON for the Key type.

    6. Click Create.

      A New private key window is displayed and the private key for the is downloaded automatically.

    7. Click Close.

    8. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON key that was downloaded. For example, in Powershell:

      # For this powershell session.
      PS > $env:GOOGLE_APPLICATION_CREDENTIALS = "$env:USERPROFILE\Downloads\your-project-id-dea9fa230eae3.json"
      # For all processes created after this command.
      PS > [Environment]::SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "$env:USERPROFILE\Downloads\your-project-id-dea9fa230eae3.json", "User")
      

Download the sample

  1. Download the sample app and extract it.

  2. If you're using the command line, navigate into the app directory, dotnet-docs-samples\appengine\flexible\.

Edit project configuration and install dependencies

In appsettings.json, set BucketName; this value is the name of the Cloud Storage bucket you created previously.

{
  "GoogleCloudStorage": {
    "BucketName": "your-google-bucket-name"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Application code

The sample application presents a web page prompting the user to supply a file to be stored in Cloud Storage. When the user selects a file and clicks submit, the upload handler loads the file content into a blob and writes it to Cloud Storage.

Notice that after the file is uploaded to Cloud Storage, the public URL to this file is returned, which you can use to serve the file directly from Cloud Storage. You should store this value in your app for future use.

    public class HomeController : Controller
    {
        // Contains the bucket name and object name
        readonly CloudStorageOptions _options;
        // The Google Cloud Storage client.
        readonly StorageClient _storage;

        public HomeController(IOptions<CloudStorageOptions> options)
        {
            _options = options.Value;
            _storage = StorageClient.Create();
        }

        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var model = new HomeIndex();
            try
            {
                // Get the storage object.
                var storageObject = 
                    await _storage.GetObjectAsync(_options.BucketName, _options.ObjectName);
                // Get a direct link to the storage object.
                model.MediaLink = storageObject.MediaLink;
                // Download the storage object.
                MemoryStream m = new MemoryStream();
                await _storage.DownloadObjectAsync(
                    _options.BucketName, _options.ObjectName, m);
                m.Seek(0, SeekOrigin.Begin);
                byte[] content = new byte[m.Length];
                m.Read(content, 0, content.Length);
                model.Content = Encoding.UTF8.GetString(content);
            }
            catch (GoogleApiException e)
            when (e.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
            {
                // Does not exist yet.  No problem.
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Index(Form sendForm)
        {
            var model = new HomeIndex();
            // Take the content uploaded in the form and upload it to
            // Google Cloud Storage.
            await _storage.UploadObjectAsync(
                _options.BucketName, _options.ObjectName, "text/plain",
                new MemoryStream(Encoding.UTF8.GetBytes(sendForm.Content)));
            model.Content = sendForm.Content;
            model.SavedNewContent = true;
            var storageObject =
                await _storage.GetObjectAsync(_options.BucketName, _options.ObjectName);
            model.MediaLink = storageObject.MediaLink;
            return View(model);
        }
    }

For more information

For complete information on Cloud Storage, see the Cloud Storage documentation.

Send feedback about...

App Engine flexible environment for .NET docs