VintaSoft Barcode .NET SDK 15.3: Документация для Веб разработчика
В этом разделе
    Распознавание штрих-кодов из изображения в приложении "React.js и ASP.NET Core"
    В этом разделе
    Данное руководство демонстрирует, как создать пустое приложение "React.js и ASP.NET Core" в Visual Studio .NET 2026 и распознать штрих-коды в изображении в приложении "React.js и ASP.NET Core".

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

      Откройте Visual Studio .NET 2026 и создайте новый проект типа "приложение React.js и ASP.NET Core":

      Настройте проект для использования .NET 10.0:

    2. Проект "ReactApp1.Server": Добавьте ссылки на nuget-пакеты Vintasoft в приложение ASP.NET Core.

      Добавьте ссылки на nuget-пакеты "Vintasoft.Barcode", "Vintasoft.Barcode.SkiaSharp" и "Vintasoft.Barcode.AspNetCore.ApiControllers" в проект "ReactApp1.Server".
    3. Проект "ReactApp1.Server": Добавьте контроллер 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)
                {
                }
        
            }
        }
        
        
    4. Проект "ReactApp1.Server": Укажите файл изображения, содержащего штрих-коды.

      Создайте папку "wwwroot\UploadedImageFiles\SessionID" в проекте "ReactApp1.Server" и скопируйте файл изображения с штрих-кодами "VintaSoft\Barcode .NET 15.3\Images\AllSupportedBarcodes.png" в созданную папку. Мы будем распознавать штрих-коды в этом изображении.
    5. Проект "ReactApp1.Server": Добавьте ссылку на nuget-пакет "Microsoft.AspNetCore.Mvc.NewtonsoftJson" для десериализации результатов распознавания штрих-кодов.

      • Добавьте ссылку на nuget-пакет "Microsoft.AspNetCore.Mvc.NewtonsoftJson" в проект "ReactApp1.Server":


      • Откройте файл "Program.cs" и добавьте строку кода "builder.Services.AddControllersWithViews().AddNewtonsoftJson();". Это необходимо для корректной десериализации результатов распознавания штрих-кодов.

        Вот исходный код файла Program.cs:
        var builder = WebApplication.CreateBuilder(args);
        
        // Add services to the container.
        
        builder.Services.AddControllers().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();
        
        
    6. Проект "ReactApp1.Server": Удалите не нужные файлы.

      Удалите файлы "ReactApp1.Server.http", "WeatherForecast.cs" и "Controllers\WeatherForecastController.cs" в проекте "ReactApp1.Server" - контроллер Web API WeatherForecast в этом примере не нужен.
    7. Проект "reactapp1.client": Скомпилируйте решение для восстановления зависимостей TypeScript в проекте "reactapp1.client".

    8. Проект "reactapp1.client": Добавьте файлы JavaScript в приложение ASP.NET Core.

      • Скопируйте файлы Vintasoft.Shared.js и Vintasoft.Barcode.js из папки "\VintaSoft Barcode .NET 15.3\Bin\JavaScript\" в папку "public" в проекте "reactapp1.client".

      • Добавьте ссылки на файлы JavaScript Vintasoft в заголовок файла "index.html" в проекте "reactapp1.client":
        <!doctype html>
        <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <link rel="icon" type="image/svg+xml" href="/vite.svg" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>reactapp1.client</title>
        
            <script src="Vintasoft.Shared.js" type="text/javascript"></script>
            <script src="Vintasoft.Barcode.js" type="text/javascript"></script>
        </head>
        <body>
            <div id="root"></div>
            <script type="module" src="/src/main.jsx"></script>
        </body>
        </html>
        
        

    9. Проект "reactapp1.client": Создайте компонент React.js, который распознает штрих-коды в изображении и отображает результат распознавания штрих-кодов.

      • Откройте файл "src\App.jsx" в проекте "reactapp1.client", очистите файл, добавьте код JavaScript в файл "App.jsx" (функция "App" генерирует разметку страницы и запускает распознавание штрих-кодов, функция "__recognizeBarcodes" распознает штрих-коды в изображении):


        Вот код JavaScript из файла App.jsx:
        import './App.css'
        
        function App() {
            return (
                <>
                    <div>
                        <h1>React.js Barcode Reader Demo</h1>
        
                        <div id="barcodeInformation"></div>
                    </div>
                    <script>{setTimeout(__recognizeBarcodes, 10)}</script>
                </>
            )
        }
        
        /**
         * Recognizes barcode in image.
         */
        function __recognizeBarcodes() {
            // declare reference to the Vintasoft namespace
            let Vintasoft = window.Vintasoft;
        
            // set the session identifier
            Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
        
            // create service that allows to recognize barcodes
            var barcodeService = new Vintasoft.Shared.WebServiceControllerJS("/vintasoft/api/MyVintasoftBarcodeApi");
        
            // create the barcode reader
            var barcodeReader = new Vintasoft.Barcode.WebBarcodeReaderJS(barcodeService);
            // specify that Code39 barcode must be searched
            barcodeReader.get_Settings().set_BarcodeType(new Vintasoft.Barcode.WebBarcodeTypeEnumJS("Code39"));
        
            // create web image that references to a file "AllSupportedBarcodes.png" in directory "/UploadedImageFiles/SessionID/"
            var imageSource = new Vintasoft.Shared.WebImageSourceJS("AllSupportedBarcodes.png");
            var image = new Vintasoft.Shared.WebImageJS(imageSource, 0);
        
            // send an asynchronous request for barcode recognition
            barcodeReader.readBarcodes(image, __readBarcodes_success, __readBarcodes_fail);
        }
        
        /**
         * Barcodes are recognized successfully.
         */
        function __readBarcodes_success(data) {
            if (data.success) {
                // get the barcode recognition result
                var barcodeRecognitionResults = data.results;
        
                var htmlMarkup = '';
                // if no barcodes found
                if (barcodeRecognitionResults.length == 0) {
                    htmlMarkup = 'No barcodes found.';
                }
                // if barcodes are found
                else {
                    htmlMarkup = barcodeRecognitionResults.length.toString() + ' barcodes are found.<br />';
                    htmlMarkup += '<br />';
        
                    // for each recognized barcode
                    for (var i = 0; i < barcodeRecognitionResults.length; i++) {
                        // get the barcode recognition result
                        var barcodeRecognitionResult = barcodeRecognitionResults[i];
        
                        // output information about recognized barcode
                        htmlMarkup += '[' + (i + 1) + ':' + barcodeRecognitionResult.barcodeType + ']<br />';
                        htmlMarkup += '  Value: ' + barcodeRecognitionResult.value + '<br />';
                        htmlMarkup += '  Confidence: ' + barcodeRecognitionResult.confidence + '<br />';
                        htmlMarkup += '  Reading quality: ' + barcodeRecognitionResult.readingQuality.toFixed(2) + '<br />';
                        htmlMarkup += '  Threshold: ' + barcodeRecognitionResult.threshold + '<br />';
                        htmlMarkup += '  Region: ' +
                            'LT=(' + barcodeRecognitionResult.region.leftTop.x + ',' + barcodeRecognitionResult.region.leftTop.y + '); ' +
                            'RT=(' + barcodeRecognitionResult.region.rightTop.x + ',' + barcodeRecognitionResult.region.rightTop.y + '); ' +
                            'LB=(' + barcodeRecognitionResult.region.leftBottom.x + ',' + barcodeRecognitionResult.region.leftBottom.y + '); ' +
                            'RB=(' + barcodeRecognitionResult.region.rightBottom.x + ',' + barcodeRecognitionResult.region.rightBottom.y + '); ' +
                            'Angle=' + barcodeRecognitionResult.region.angle.toFixed(1) + '°<br />';
        
                        htmlMarkup += '<br />';
                    }
                }
        
                var barcodeInformationElement = document.getElementById("barcodeInformation");
                barcodeInformationElement.innerHTML = htmlMarkup;
            }
        }
        
        /**
         * Barcode recognition is failed.
         */
        function __readBarcodes_fail(data) {
            // show information about error
            alert(data.errorMessage);
        }
        
        export default App
        
        

      • Откройте файл "Properties\launchSettings.json" в проекте "ReactApp1.Server" и получите URL веб-сервиса из параметра "applicationUrl" раздела "profiles\https" - в этом примере URL - "https://localhost:7109":


        Откройте файл "vite.config.js" в проекте "reactapp1.client" и укажите, что приложение React.js может иметь доступ к веб-сервису в проекте "ReactApp1.Server" (добавьте раздел "server" в объект "defineConfig"):
        import { defineConfig } from 'vite'
        import react from '@vitejs/plugin-react'
        
        const target = 'https://localhost:7109';
        
        // https://vite.dev/config/
        export default defineConfig({
            plugins: [react()],
            server: {
                proxy: {
                    '^/vintasoft/api/': {
                        target,
                        secure: false
                    }
                },
                port: 7109
            }
        })
        
        

    10. Запустите приложение "React.js with ASP.NET Core" и посмотрите результат.