VintaSoft Barcode .NET SDK 15.0: Документация для Веб разработчика
В этом разделе
    Генерация изображения штрих-кода в приложении ASP.NET Core
    В этом разделе
    Данное руководство демонстрирует, как создать пустое веб-приложение ASP.NET Core в Visual Studio .NET 2022 и сгенерировать изображение штрих-кода в приложении ASP.NET Core.


    Вот шаги, которые необходимо выполнить:
    1. Создайте пустое веб-приложение ASP.NET Core.

      Запустите Visual Studio .NET 2022 и создайте новый проект, тип проекта - веб-приложение ASP.NET Core:

      Включите в проекте использование .NET 8.0:

    2. Серверная сторона: Добавьте ссылки на сборки Vintasoft в веб-приложение ASP.NET Core.

      Добавьте ссылки на сборки Vintasoft.Barcode.dll, Vintasoft.Barcode.SkiaSharp.dll, Vintasoft.Shared.dll, Vintasoft.Shared.Web.dll, Vintasoft.Barcode.Web.Services.dll и Vintasoft.Barcode.AspNetCore.ApiControllers.dll из папки "<InstallPath>\VintaSoft Barcode .NET v15.0\Bin\DotNet8\AnyCPU\" в веб-приложение ASP.NET Core.
      Комментарий: Ссылка на сборку Vintasoft.Barcode.SkiaSharp.dll необходима только в том случае, если SDK должен рисовать текстовое значение штрих-кода на изображении штрих-кода. Вместо сборки Vintasoft.Barcode.SkiaSharp.dll можно использовать Vintasoft.Barcode.ImageSharp.dll.

    3. Серверная сторона: Добавьте контроллер Web API, который позволяет генерировать изображение штрих-кода.

      • Добавьте в проект папку "Controllers".
      • Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
      • Выберите шаблон контроллера "Empty API", задайте имя контроллера "MyVintasoftBarcodeApiController" и нажмите кнопку "Add"
      • Укажите, что класс MyVintasoftBarcodeApiController является производным от класса Vintasoft.Barcode.AspNetCore.ApiControllers.VintasoftBarcodeApiController

        Вот исходные коды класса MyVintasoftBarcodeApiController:
        using Microsoft.AspNetCore.Hosting;
        using Microsoft.AspNetCore.Mvc;
        using Vintasoft.Barcode.AspNetCore.ApiControllers;
        
        namespace WebApplication1.Controllers
        {
            public class MyVintasoftBarcodeApiController : VintasoftBarcodeApiController
            {
        
                public MyVintasoftBarcodeApiController(IWebHostEnvironment hostingEnvironment)
                    : base(hostingEnvironment)
                {
                }
        
            }
        }
        
        
    4. Серверная сторона: Создайте контроллер MVC для веб-представления, которое будет отображать сгенерированный штрих-код.

      • Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
      • Выберите шаблон "MVC Controller - Empty", задайте имя контроллера "HomeController" и нажмите кнопку "Add"
      • Откройте файл "Program.cs", добавьте контроллеры с представлениями в сервисы приложения ASP.NET Core:

        Добавьте созданный контроллер MVC к конечным точкам приложения ASP.NET Core:

        Вот исходные коды C# файла Startup.cs:
        var builder = WebApplication.CreateBuilder(args);
        
        // Add services to the container.
        builder.Services.AddRazorPages();
        builder.Services.AddControllersWithViews();
        
        var app = builder.Build();
        
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        
        app.UseRouting();
        
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        });
        
        app.MapRazorPages();
        
        app.Run();
        
    5. Клиентская сторона: Создайте веб-представление для отображения сгенерированного штрих-кода.

      • Откройте файл "HomeController.cs", нажмите правую кнопку мыши на методе "Index" класса HomeController и выберите "Add View..." в контекстном меню
      • Выберите шаблон "Razor View - Empty", нажмите кнопку "Add", задайте имя представления "Index" и нажмите кнопку "Add" => Будет создан файл "Views\Home\Index.cshtml"
    6. Клиентская сторона: Добавьте в проект файлы Vintasoft JavaScript.

      • Добавьте папку "wwwroot\Scripts\" в приложение ASP.NET Core.

      • Скопируйте файлы Vintasoft.Shared.js и Vintasoft.Barcode.js из папки "<InstallPath>\VintaSoft Barcode .NET v15.0\Bin\JavaScript\" в папку "wwwroot\Scripts\".
    7. Клиентская сторона: Добавьте в веб-представление код JavaScript, который генерирует и отображает изображение штрих-кода.

      • Откройте веб-представление - файл "Views\Home\Index.cshtml".
      • Добавьте базовый код:

        Вот HTML-код:
        @{
            Layout = null;
        }
        
        <html>
        <head>
            <meta name="viewport" content="width=device-width" />
            <title>ASP.NET Core Barcode Generator Demo</title>
        
        </head>
        <body>
        
        </body>
        </html>
        
        
      • Добавьте ссылки на файлы Vintasoft JavaScript:

        Вот HTML-код, который добавляет ссылки на файлы Vintasoft JavaScript:
        <script src="~/Scripts/Vintasoft.Shared.js" type="text/javascript"></script>
        <script src="~/Scripts/Vintasoft.Barcode.js" type="text/javascript"></script>
        
        
      • Добавьте в веб-представление HTML-разметку (элемент image, который будет отображать сгенерированное изображение штрих-кода):

        Вот код HTML-разметки:
        <img id="barcodeImage" src="" />
        
        
      • Добавьте код JavaScript, который генерирует и отображает изображение штрих-кода:

        Вот код JavaScript, который генерирует и отображает изображение штрих-кода:
        <script type="text/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");
        </script>
        
        
      • Удалите папку "Pages".
    8. Запустите приложение ASP.NET Core и оцените результат.