Azure

Tips on how to Add Information into Azure Blob Storage with ASP.NET Core Internet API

We’re going to divide this text into the next sections:

  • Creating Azure Storage
  • Add Information to Azure with ASP.NET Core Internet API

Creating Azure Storage

The very first thing we’ve got to do is to navigate and register to Azure Portal the place we are able to create our storage. If we don’t have a subscription, we are able to create a free subscription account on the dashboard.

Subsequent, we’re going to create a brand new storage account service:

Another view of the storage creation process.

After these steps are executed, we’re going to click on the Subsequent button two occasions till our validation will get handed.

Validation completion after clicking the Next button.

We’re going to modify the appsettings.json file by including a connection string part:


{
  "ConnectionStrings": {
    "EmployeeAppcon": "Knowledge Supply=****.mysql.database.azure.com;preliminary catalog=databaseName;Consumer id=****; Pwd=***",
    "AzureBlobStorage": "DefaultEndpointsProtocol=https;AccountName=authoringsite;AccountKey=X+55***3SgA==;EndpointSuffix=core.home windows.internet"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Info",
      "Microsoft": "Warning",
      "Microsoft.Internet hosting.Lifetime": "Info"
    }
  },
  "AllowedHosts": "*"
}

We are able to discover this connection string within the Entry keys menu that we have already got opened:

Location of the connection string in the Access keys menu.

Subsequent, create a brand new venture in Visual Studio.

Creating a new project in Visual Studio.

Choose ASP.Web Core Internet Software.

Selecting ASP.Net Core Web Application in Visual Studio.

Present the Venture identify and placement.

Entering project name and location in Visual Studio.

Choose Goal Framework and click on on the Create button.

Selecting Target Framework and creating the project.

As soon as the venture is created a fundamental view of the answer is explored.

Exploring the basic view of the solution in Visual Studio.

We have to create two folders with names controllers and fashions.

Creating controllers and models folders.

Want to put in dependency from Genet packages.

MySql.Knowledge.dll
Microsoft.AspNetCore.Mvc.NewtonsoftJson.dll – model 3.1.10
Azure.Storage.Blobs – model 12.1.0

Please replace the under the road in startup.js

// added scope to azure blob storage
companies.AddScoped(x => new BlobServiceClient(Configuration.GetValue<string>("ConnectionStrings:AzureBlobStorage")));

Subsequent, we have to create AssetUploadController.cs

Creating AssetUploadController.cs

utilizing Azure.Storage.Blobs;
utilizing Azure.Storage.Blobs.Fashions;
utilizing createwebapiusingmysql.Fashions;
utilizing Microsoft.AspNetCore.Mvc;
utilizing Microsoft.Extensions.Configuration;
utilizing MySql.Knowledge.MySqlClient;
utilizing System;
utilizing System.Collections.Generic;
utilizing System.Knowledge;
utilizing System.Linq;
utilizing System.Threading.Duties;

namespace createwebapiusingmysql.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AssetUploadController : Controller
    {
        non-public readonly string _azureConnectionString;
        non-public readonly string _azureConnectionStringsastoken;
        non-public readonly IConfiguration _configuration;

        public AssetUploadController(IConfiguration configuration)
        {
            _azureConnectionString = configuration.GetConnectionString("AzureBlobStorage");
            _azureConnectionStringsastoken = configuration.GetConnectionString("SASToken");
            _configuration = configuration;
        }

        Record<Merchandise> _category = new Record<Merchandise>();

        [HttpPost("{id}")]
        public async Process<IActionResult> assetAsync(int id)
        {
            attempt
            {
                GetcategoryFriendlyame(id);
                string containersname = _category[0].categoryFriendlyame;
                var formCollection = await Request.ReadFormAsync();
                var file = formCollection.Information.First();

                if (file.Size > 0)
                {
                    var container = new BlobContainerClient(_azureConnectionString, containersname);
                    var createResponse = await container.CreateIfNotExistsAsync();

                    if (createResponse != null && createResponse.GetRawResponse().Standing == 201)
                        await container.SetAccessPolicyAsync(Azure.Storage.Blobs.Fashions.PublicAccessType.Blob);

                    var blob = container.GetBlobClient(file.FileName);

                    await blob.DeleteIfExistsAsync((Azure.Storage.Blobs.Fashions.DeleteSnapshotsOption)Azure.Storage.Blobs.Fashions.DeleteSnapshotsOption.IncludeSnapshots);

                    utilizing (var fileStream = file.OpenReadStream())
                    {
                        await blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType = file.ContentType });
                        blob.SetMetadata(new Dictionary<string, string>());

                        Dictionary<string, string> metadata = new Dictionary<string, string>(2);
                        metadata.Add("ProductId", id.ToString());
                        blob.SetMetadata(metadata);
                    }

                    if (blob.Uri.ToString() != null && blob.Uri.ToString() != "")
                    {
                        UpdateProductTable(id.ToString(), blob.Uri.ToString());
                    }

                    return Okay(blob.Uri.ToString());
                }

                return BadRequest();
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Inner server error: {ex}");
            }
        }

        // we're getting class identify to create container in azure
        non-public Record<Merchandise> GetcategoryFriendlyame(int id)
        {
            var @ProductId = id;
            string question = @"choose categoryFriendlyame, ProductId from restapi.classes, restapi.merchandise the place classes.categoryid = merchandise.categoryid AND merchandise.ProductId=" + @ProductId + ";";
            DataTable desk = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
            MySqlDataReader myReader;

            utilizing (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
            {
                mycon.Open();
                utilizing (MySqlCommand mycommond = new MySqlCommand(question, mycon))
                {
                    myReader = mycommond.ExecuteReader();
                    desk.Load(myReader);
                    myReader.Shut();
                    mycon.Shut();
                }

                for (int i = 0; i < desk.Rows.Rely; i++)
                {
                    Merchandise prd = new Merchandise();
                    prd.ProductId = Convert.ToInt32(desk.Rows[i]["ProductId"]);
                    prd.categoryFriendlyame = desk.Rows[i]["categoryFriendlyame"].ToString();
                    _category.Add(prd);
                }
                return (_category);
            }
        }

        // We're updating picture and mannequin url to subject in product desk
        non-public void UpdateProductTable(string v1, string v2)
        {
            string imageuri = v2;
            var splitVals = imageuri.Cut up('/');
            var URL4 = splitVals[3];
            var URL5 = splitVals[4];
            string subseturi = "https://ceeademocontent.azureedge.internet";
            var sastoken = _azureConnectionStringsastoken;
            string finalurl = "" + subseturi + "/" + URL4 + "/" + URL5 + sastoken;
            string imagetype = URL5.Substring(URL5.Size - 4);
            string question;

            if (imagetype.ToString() == "gltf" || imagetype.ToString() == ".glb")
            {
                question = @"replace restapi.Merchandise set productModel="{finalurl}" the place productId = {v1}";
                question = question.Change("{finalurl}", finalurl);
                question = question.Change("{v1}", v1);
            }
            else
            {
                question = @"replace restapi.Merchandise set productPreview = '{finalurl}' the place productId = {v1}";
                question = question.Change("{finalurl}", finalurl);
                question = question.Change("{v1}", v1);
            }

            DataTable desk = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
            MySqlDataReader myReader;

            utilizing (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
            {
                mycon.Open();
                utilizing (MySqlCommand mycommond = new MySqlCommand(question, mycon))
                {
                    myReader = mycommond.ExecuteReader();
                    desk.Load(myReader);
                    myReader.Shut();
                    mycon.Shut();
                }
            }
        }
    }
}

Lastly, with Postman attempt to add the file to Azure blob storage as proven within the under display.

Demonstration of using Postman to add a file to Azure blob storage.

Know extra about our firm at Skrots. Know extra about our companies at Skrots Companies, Additionally checkout all different blogs at Weblog at Skrots

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button