Генерация изображения штрих-кода в ASP.NET Core приложении
В этом разделе
Данное руководство демонстрирует, как создать пустое веб-приложение ASP.NET Core в Visual Studio .NET 2026 и сгенерировать изображение штрих-кода в приложении ASP.NET Core.
Вот шаги, которые необходимо выполнить:
-
Создайте пустое веб-приложение ASP.NET Core.
Откройте Visual Studio .NET 2026 и создайте новый проект приложения типа "ASP.NET Core Web App (Model-View-Controller)":
Настройте проект для использования .NET 10.0:
-
Серверная сторона: Добавьте ссылки на nuget-пакеты Vintasoft в приложение ASP.NET Core.
Добавьте ссылки на nuget-пакеты "Vintasoft.Barcode", "Vintasoft.Barcode.SkiaSharp" и "Vintasoft.Barcode.AspNetCore.ApiControllers" в проект ASP.NET Core.
Комментарий:
Ссылка на nuget-пакет "Vintasoft.Barcode.Gdi" необходима только в том случае, если SDK должен отображать текстовое значение штрих-кода на изображении штрих-кода. Вместо nuget-пакета "Vintasoft.Barcode.Gdi" можно использовать nuget-пакет "Vintasoft.Barcode.ImageSharp" или "Vintasoft.Barcode.SkiaSharp".
-
Серверная часть: Добавьте контроллер Web API, который позволяет генерировать изображение штрих-кода.
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
-
Выберите пустой шаблон API-контроллера, задайте имя контроллера как "MyVintasoftBarcodeApiController" и нажмите кнопку "Добавить".
-
Укажите, что класс MyVintasoftBarcodeApiController является производным от класса Vintasoft.Barcode.AspNetCore.ApiControllers.VintasoftBarcodeApiController.
Вот исходный код класса MyVintasoftBarcodeApiController:
using Vintasoft.Barcode.AspNetCore.ApiControllers;
namespace WebApplication1.Controllers
{
public class MyVintasoftBarcodeApiController : VintasoftBarcodeApiController
{
public MyVintasoftBarcodeApiController(IWebHostEnvironment hostingEnvironment)
: base(hostingEnvironment)
{
}
}
}
-
Серверная часть: Укажите, что VintaSoft Barcode .NET SDK должен использовать библиотеку SkiaSharp для отрисовки 2D-графики.
Откройте файл "Program.cs" и добавьте строку кода "Vintasoft.Barcode.SkiaSharpAssembly.Init();" в начало файла:
Вот исходные коды файла Program.cs:
// specify that VintaSoft Barcode .NET SDK should use SkiaSharp library for drawing of 2D graphics
Vintasoft.Barcode.SkiaSharpAssembly.Init();
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews().AddNewtonsoftJson();
var app = builder.Build();
app.UseDefaultFiles();
app.MapStaticAssets();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("/index.html");
app.Run();
-
Клиентская сторона: Добавьте в проект файлы Vintasoft JavaScript.
-
Добавьте папку "wwwroot\lib\Vintasoft" в приложение ASP.NET Core.
-
Скопируйте файлы Vintasoft.Shared.js и Vintasoft.Barcode.js из папки "\VintaSoft Barcode .NET 15.3\Bin\JavaScript" в папку "wwwroot\lib\Vintasoft".
-
Клиентская сторона: Добавьте в веб-представление код JavaScript, который генерирует штрих-код и отображает сгенерированное изображение штрих-кода.
-
Откройте файл "Views\Home\Index.cshtml", очистите файл, добавьте HTML-код (ссылки на файлы JavaScript VintaSoft; IMG-элемент, который будет отображать сгенерированное изображение штрих-кода) в файл "Index.cshtml":
Вот HTML-код файла "Index.cshtml":
@{
ViewData["Title"] "blue">Title"] = "Home Page";
}
<script src="~/lib/Vintasoft/Vintasoft.Shared.js" type="text/javascript"></script>
<script src="~/lib/Vintasoft/Vintasoft.Barcode.js" type="text/javascript"></script>
<img id="barcodeImage" src="" />
-
Откройте файл "wwwroot\js\site.js", очистите файл, добавьте код JavaScript (генерирует изображение штрих-кода и отображает сгенерированное изображение штрих-кода) в файл "site.js":
Вот код JavaScript, который генерирует изображение штрих-кода и отображает сгенерированное изображение штрих-кода:
/**
* Generates 1D barcode image.
*/
function generate1dBarcodeImage(barcodeType, barcodeValue) {
// create service that allows to generate barcode
var barcodeService = new Vintasoft.Shared.WebServiceControllerJS("/vintasoft/api/MyVintasoftBarcodeApi");
// create the barcode writer
var barcodeWriter = new Vintasoft.Barcode.WebBarcodeWriterJS(barcodeService);
// create the barcode writer settings for generating 1D barcode
var barcodeWriterSettings = new Vintasoft.Barcode.Web1DBarcodeWriterSettingsJS();
// specify that barcode writer must generate QR barcode image
barcodeWriterSettings.set_BarcodeType(new Vintasoft.Barcode.Web1DBarcodeTypeEnumJS(barcodeType));
// specify the Code128 barcode value
barcodeWriterSettings.set_Value(barcodeValue);
// specify settings for barcode writer
barcodeWriter.set_Settings(barcodeWriterSettings);
// send an asynchronous request for getting barcode image as Base64 string
barcodeWriter.getBarcodeAsBase64Image(__writeBarcode_success, __writeBarcode_failed);
}
/**
* Generates 2D barcode image.
*/
function generate2dBarcodeImage(barcodeType, barcodeValue) {
// create web service that allows to generate barcode
var barcodeService = new Vintasoft.Shared.WebServiceControllerJS("/vintasoft/api/MyVintasoftBarcodeApi");
// create the barcode writer
var barcodeWriter = new Vintasoft.Barcode.WebBarcodeWriterJS(barcodeService);
// create the barcode writer settings for generating 2D barcode
var barcodeWriterSettings = new Vintasoft.Barcode.Web2DBarcodeWriterSettingsJS();
// specify that barcode writer must generate QR barcode image
barcodeWriterSettings.set_BarcodeType(new Vintasoft.Barcode.Web2DBarcodeTypeEnumJS(barcodeType));
// specify the QR barcode value
barcodeWriterSettings.set_Value(barcodeValue);
// specify settings for barcode writer
barcodeWriter.set_Settings(barcodeWriterSettings);
// send an asynchronous request for getting barcode image as Base64 string
barcodeWriter.getBarcodeAsBase64Image(__writeBarcode_success, __writeBarcode_failed);
}
/**
* Barcode is generated successfully.
*/
function __writeBarcode_success(data) {
if (data.success) {
var barcodeImage = data.barcodeImage;
document.getElementById("barcodeImage").src = barcodeImage;
}
else {
alert(data.errorMessage);
}
}
/**
* Barcode generation is failed.
*/
function __writeBarcode_failed(data) {
// show information about error
alert(data.errorMessage);
}
// set the session identifier
Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
// generate image of QR barcode with value "12345"
generate2dBarcodeImage("QR", "12345");
-
Запустите приложение ASP.NET Core и посмотрите результат.