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:
After these steps are executed, we’re going to click on the Subsequent button two occasions till our validation will get handed.
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:
Subsequent, create a brand new venture in Visual Studio.
Choose ASP.Web Core Internet Software.
Present the Venture identify and placement.
Choose Goal Framework and click on on the Create button.
As soon as the venture is created a fundamental view of the answer is explored.
We have to create two folders with names controllers and fashions.
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("ConnectionStrings:AzureBlobStorage")));
Subsequent, we have to create 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 _category = new Record();
[HttpPost("id")]
public async Process 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());
Dictionary metadata = new Dictionary(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 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)
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.
Know extra about our firm at Skrots. Know extra about our companies at Skrots Companies, Additionally checkout all different blogs at Weblog at Skrots
Know more about our company at Skrots. Know more about our services at Skrots Services, Also checkout all other blogs at Blog at Skrots
Thanks, Harsh
Founder | CEO — Skrots
Learn more about our blog at Blog at Skrots. Checkout our list of services on Skrots. Give a look at our website design at Skrots . Checkout our LinkedIn Page at LinkedIn.com. Check out our original post at https://blog.skrots.com/how-to-upload-files-into-azure-blob-storage-with-asp-net-core-web-api/?feed_id=1518&_unique_id=654f2450e32d6