跳至页脚内容
USING IRONBARCODE

ASP.NET条形码扫描器:使用IronBarcode实现文件上传和 REST API

在ASP.NET中使用IronBarcode进行条码扫描变得简单:通过NuGet安装,调用BarcodeReader.Read(),并在一步中获取类型、置信度和位置数据的解码值——无需复杂的配置。

条码扫描是现代Web应用程序中的标准要求,支持库存管理、文档处理和票务验证工作流程。 根据GS1的数据,全球每天有超过60亿次交易使用条形码,这一数字充分说明了对于任何业务系统来说,准确的条码阅读是多么的重要。 ISO/IEC 15415标准定义了二维条码符号的质量度量,而ISO/IEC 15416标准则涵盖了一维线性条码,这两者都是IronBarcode本地支持的。

本指南向您展示如何使用IronBarcode将可靠的条码扫描添加到您的ASP.NET Core应用程序中,涵盖安装、文件上传处理、REST API集成和生产部署模式。 最终,您将拥有用于Razor页面文件上传扫描器和可接受任何客户端提供的base64编码图像的JSON API端点的工作代码。

如何在ASP.NET项目中安装IronBarcode?

入门只需几分钟。 该库支持ASP.NET Core和传统ASP.NET MVC应用程序,适用于各种项目类型的适配。企业部署同样在AzureAWS LambdaDocker容器上良好运行。 库的机器学习驱动检测通过自动应用复杂的图像校正来处理具有挑战性的条码图像,这在处理在各种光照条件下用移动相机拍摄的照片时特别有用。

通过NuGet包管理器安装

在 Visual Studio 中打开软件包管理器控制台并运行:

Install-Package BarCode
Install-Package BarCode
SHELL

或者,使用.NET CLI:

dotnet add package BarCode
dotnet add package BarCode
SHELL

或者在Visual Studio NuGet包管理器UI中搜索"BarCode"并点击安装。 软件包会自动管理所有依赖项。

对于特定平台的部署,请考虑使用针对目标环境优化的平台专用NuGet包。 该库提供标准和BarCode.Slim包以适应不同的部署方案。 有关完整的安装指南,请参见IronBarcode安装指南

配置您的项目

安装后,将必要的using语句添加到您的C#文件中:

using IronBarCode;
using IronBarCode;
$vbLabelText   $csharpLabel

这种导入让您可以访问IronBarcode的完整条码阅读生成能力。 该库支持超过30种条码格式,包括QR码、Code 128、Code 39、数据矩阵和PDF417。查看支持的条码格式列表以确认您的用例兼容性。

有关安装问题的故障排除,请参考NuGet包故障排除指南或提交工程请求以获得专业支持。

选择正确的架构模式

在ASP.NET中实现条码扫描时,您有两种主要的架构方法。 了解这些模式有助于您为每个用例选择正确的条码阅读器设置

// Server-side processing -- recommended for most ASP.NET scenarios
var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Balanced,
    ExpectMultipleBarcodes = true,
    UseConfidenceThreshold = true,
    ConfidenceThreshold = 0.85
};

var results = BarcodeReader.Read(stream, options);

foreach (var barcode in results)
{
    Console.WriteLine($"Type: {barcode.BarcodeType}, Value: {barcode.Text}");
}
// Server-side processing -- recommended for most ASP.NET scenarios
var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Balanced,
    ExpectMultipleBarcodes = true,
    UseConfidenceThreshold = true,
    ConfidenceThreshold = 0.85
};

var results = BarcodeReader.Read(stream, options);

foreach (var barcode in results)
{
    Console.WriteLine($"Type: {barcode.BarcodeType}, Value: {barcode.Text}");
}
$vbLabelText   $csharpLabel

服务器端方法为图像处理提供最大控制,并且在所有浏览器中保持一致性。 当服务器处理每个图像时,您还可以获得一个干净的审计轨迹:每个扫描的条码都通过您的应用程序层,您可以在其中记录、验证数据库或触发下游工作流程。 这种模式特别适用于医疗、物流和制造等受监管行业,其中每一个扫描都必须被记录。

对于客户端相机捕获集成,现代浏览器支持用于相机访问的MediaDevices API,它可以与通过REST API的IronBarcode服务器端处理相结合——本指南后续部分将详细介绍。选择服务器端处理也简化了您的安全模型:没有敏感的处理逻辑暴露给浏览器,所有验证都发生在您的应用程序边界内。

客户端与服务器端条码扫描权衡
方面 客户端捕获+服务器处理 纯服务器端处理
最适合 实时摄像头扫描 批量处理,文件上传
浏览器支持 仅现代浏览器 所有浏览器
用户体验 即时反馈 标准上传流程
安全模型 更复杂(CORS,认证) 简单
带宽使用 较低(设备上预处理) 较高(原始图像上传)

如何实现文件上传条码扫描?

文件上传扫描是ASP.NET Web应用程序中最常见的条码场景。 此模式适用于处理发票、运输标签或任何嵌入条码的文档。 为了提高吞吐量,考虑实施异步条码阅读以同时处理多个上传。

构建上传表单

在您的ASP.NET视图中创建响应式HTML表单:

@* Razor view -- barcode upload form *@
<form method="post" enctype="multipart/form-data" id="barcodeForm">
    <div class="form-group">
        <label for="barcodeFile">Select Barcode Image:</label>
        <input type="file" name="barcodeFile" id="barcodeFile"
               accept="image/*,.pdf" class="form-control"
               capture="environment" />
    </div>
    <button type="submit" class="btn btn-primary" id="scanBtn">
        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
        Scan Barcode
    </button>
</form>
<div id="results">
    @ViewBag.BarcodeResult
</div>
@* Razor view -- barcode upload form *@
<form method="post" enctype="multipart/form-data" id="barcodeForm">
    <div class="form-group">
        <label for="barcodeFile">Select Barcode Image:</label>
        <input type="file" name="barcodeFile" id="barcodeFile"
               accept="image/*,.pdf" class="form-control"
               capture="environment" />
    </div>
    <button type="submit" class="btn btn-primary" id="scanBtn">
        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
        Scan Barcode
    </button>
</form>
<div id="results">
    @ViewBag.BarcodeResult
</div>
$vbLabelText   $csharpLabel

capture="environment"属性在移动设备上启动后置摄像头,让用户在无需JavaScript的情况下获得本机相机般的体验。

实现安全的后端处理

控制器操作处理文件验证、内存流处理和结果格式化:

[HttpPost]
[ValidateAntiForgeryToken]
[RequestSizeLimit(10_000_000)] // 10MB limit
public async Task<IActionResult> ScanBarcode(IFormFile barcodeFile)
{
    var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif",
                                    ".tiff", ".bmp", ".pdf" };
    var extension = Path.GetExtension(barcodeFile.FileName).ToLowerInvariant();

    if (!allowedExtensions.Contains(extension))
    {
        ModelState.AddModelError("", "Invalid file type");
        return View();
    }

    if (barcodeFile != null && barcodeFile.Length > 0)
    {
        using var stream = new MemoryStream();
        await barcodeFile.CopyToAsync(stream);
        stream.Position = 0;

        var options = new BarcodeReaderOptions
        {
            Speed = ReadingSpeed.Balanced,
            ExpectMultipleBarcodes = true,
            ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional |
                                BarcodeEncoding.QRCode |
                                BarcodeEncoding.DataMatrix,
            ImageFilters = new ImageFilterCollection
            {
                new SharpenFilter(),
                new ContrastFilter()
            }
        };

        var results = BarcodeReader.Read(stream, options);

        ViewBag.BarcodeResult = results.Any()
            ? string.Join("<br/>", results.Select(r => $"<strong>{r.BarcodeType}:</strong> {r.Text}"))
            : "No barcodes found in the image.";
    }

    return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[RequestSizeLimit(10_000_000)] // 10MB limit
public async Task<IActionResult> ScanBarcode(IFormFile barcodeFile)
{
    var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif",
                                    ".tiff", ".bmp", ".pdf" };
    var extension = Path.GetExtension(barcodeFile.FileName).ToLowerInvariant();

    if (!allowedExtensions.Contains(extension))
    {
        ModelState.AddModelError("", "Invalid file type");
        return View();
    }

    if (barcodeFile != null && barcodeFile.Length > 0)
    {
        using var stream = new MemoryStream();
        await barcodeFile.CopyToAsync(stream);
        stream.Position = 0;

        var options = new BarcodeReaderOptions
        {
            Speed = ReadingSpeed.Balanced,
            ExpectMultipleBarcodes = true,
            ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional |
                                BarcodeEncoding.QRCode |
                                BarcodeEncoding.DataMatrix,
            ImageFilters = new ImageFilterCollection
            {
                new SharpenFilter(),
                new ContrastFilter()
            }
        };

        var results = BarcodeReader.Read(stream, options);

        ViewBag.BarcodeResult = results.Any()
            ? string.Join("<br/>", results.Select(r => $"<strong>{r.BarcodeType}:</strong> {r.Text}"))
            : "No barcodes found in the image.";
    }

    return View();
}
$vbLabelText   $csharpLabel

这种实现会在处理之前验证文件类型,从内存流中读取条码,并返回所有检测到的结果。 IronBarcode处理各种图像格式,包括多页TIFF和GIF以及PDF文档,消除了特定格式处理代码。

扫描输入和输出的样子

Code 128条码编码URL 'https://ironsoftware.com/csharp/barcode/' 展示出机读条和人读文本,以便在ASP.NET条码阅读器应用程序中准确扫描

上面的例子展示了一个标准的Code 128条码——这是运输和库存应用中的常见格式。 扫描后,结果屏幕确认了解码值以及置信度元数据:

ASP.NET Core Web应用程序界面显示成功的条码扫描结果,带有文件上传表单,显示解码的Code128条码值和置信分数元数据

IronBarcode返回上传图像中检测到的每个条码的条码类型、解码值、置信度分数和位置数据。

如何构建条码扫描的REST API?

现代ASP.NET应用程序通常通过REST API公开条码扫描功能,允许与移动应用、单页应用或第三方服务集成。 此模式支持客户端相机捕获和服务器端处理。

条码API的安全注意事项

在编写控制器之前,规划安全层。 条码数据可能包含任意内容,因此始终要验证输入。 遵循IronBarcode安全指南以获得全面保护:

  • 输入验证:在存储或处理之前,清理条码内容
  • 速率限制:使用ASP.NET Core内置的速率限制中间件以防止API滥用
  • 认证:用JWT tokens或API keys保护端点
  • HTTPS强制:所有条码API流量必须通过TLS进行
  • CORS策略:限制哪些来源可以调用您的扫描端点
  • 许可证密钥管理正确应用许可证密钥并在web.config中配置它们以供生产使用

构建生产API控制器

[ApiController]
[Route("api/[controller]")]
public class BarcodeController : ControllerBase
{
    private readonly ILogger<BarcodeController> _logger;
    private readonly IMemoryCache _cache;

    public BarcodeController(ILogger<BarcodeController> logger, IMemoryCache cache)
    {
        _logger = logger;
        _cache = cache;
    }

    [HttpPost("scan")]
    [ProducesResponseType(typeof(BarcodeResponse), 200)]
    [ProducesResponseType(typeof(ErrorResponse), 400)]
    public async Task<IActionResult> ScanBarcode([FromBody] BarcodeRequest request)
    {
        try
        {
            if (string.IsNullOrEmpty(request.ImageBase64))
                return BadRequest(new ErrorResponse { Error = "Image data is required" });

            var cacheKey = $"barcode_{request.ImageBase64.GetHashCode()}";
            if (_cache.TryGetValue(cacheKey, out BarcodeResponse cachedResult))
                return Ok(cachedResult);

            byte[] imageBytes = Convert.FromBase64String(request.ImageBase64);

            if (imageBytes.Length > 10 * 1024 * 1024)
                return BadRequest(new ErrorResponse { Error = "Image size exceeds 10MB limit" });

            var options = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Faster,
                ExpectMultipleBarcodes = request.ExpectMultiple ?? false,
                UseConfidenceThreshold = true,
                ConfidenceThreshold = 0.8
            };

            var results = await Task.Run(() => BarcodeReader.Read(imageBytes, options));

            var response = new BarcodeResponse
            {
                Success = true,
                Barcodes = results.Select(r => new BarcodeData
                {
                    Type = r.BarcodeType.ToString(),
                    Value = r.Text,
                    Confidence = r.Confidence,
                    Position = new BarcodePosition
                    {
                        X = r.Points.Select(p => p.X).Min(),
                        Y = r.Points.Select(p => p.Y).Min(),
                        Width = r.Width,
                        Height = r.Height
                    }
                }).ToList()
            };

            _cache.Set(cacheKey, response, TimeSpan.FromMinutes(5));
            return Ok(response);
        }
        catch (FormatException)
        {
            return BadRequest(new ErrorResponse { Error = "Invalid base64 image data" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error processing barcode scan");
            return StatusCode(500, new ErrorResponse { Error = "Internal server error" });
        }
    }
}

public record BarcodeRequest(string ImageBase64, bool? ExpectMultiple);

public record BarcodeResponse
{
    public bool Success { get; init; }
    public List<BarcodeData> Barcodes { get; init; } = new();
}

public record BarcodeData
{
    public string Type { get; init; }
    public string Value { get; init; }
    public double Confidence { get; init; }
    public BarcodePosition Position { get; init; }
}

public record BarcodePosition(int X, int Y, int Width, int Height);

public record ErrorResponse
{
    public bool Success => false;
    public string Error { get; init; }
}
[ApiController]
[Route("api/[controller]")]
public class BarcodeController : ControllerBase
{
    private readonly ILogger<BarcodeController> _logger;
    private readonly IMemoryCache _cache;

    public BarcodeController(ILogger<BarcodeController> logger, IMemoryCache cache)
    {
        _logger = logger;
        _cache = cache;
    }

    [HttpPost("scan")]
    [ProducesResponseType(typeof(BarcodeResponse), 200)]
    [ProducesResponseType(typeof(ErrorResponse), 400)]
    public async Task<IActionResult> ScanBarcode([FromBody] BarcodeRequest request)
    {
        try
        {
            if (string.IsNullOrEmpty(request.ImageBase64))
                return BadRequest(new ErrorResponse { Error = "Image data is required" });

            var cacheKey = $"barcode_{request.ImageBase64.GetHashCode()}";
            if (_cache.TryGetValue(cacheKey, out BarcodeResponse cachedResult))
                return Ok(cachedResult);

            byte[] imageBytes = Convert.FromBase64String(request.ImageBase64);

            if (imageBytes.Length > 10 * 1024 * 1024)
                return BadRequest(new ErrorResponse { Error = "Image size exceeds 10MB limit" });

            var options = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Faster,
                ExpectMultipleBarcodes = request.ExpectMultiple ?? false,
                UseConfidenceThreshold = true,
                ConfidenceThreshold = 0.8
            };

            var results = await Task.Run(() => BarcodeReader.Read(imageBytes, options));

            var response = new BarcodeResponse
            {
                Success = true,
                Barcodes = results.Select(r => new BarcodeData
                {
                    Type = r.BarcodeType.ToString(),
                    Value = r.Text,
                    Confidence = r.Confidence,
                    Position = new BarcodePosition
                    {
                        X = r.Points.Select(p => p.X).Min(),
                        Y = r.Points.Select(p => p.Y).Min(),
                        Width = r.Width,
                        Height = r.Height
                    }
                }).ToList()
            };

            _cache.Set(cacheKey, response, TimeSpan.FromMinutes(5));
            return Ok(response);
        }
        catch (FormatException)
        {
            return BadRequest(new ErrorResponse { Error = "Invalid base64 image data" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error processing barcode scan");
            return StatusCode(500, new ErrorResponse { Error = "Internal server error" });
        }
    }
}

public record BarcodeRequest(string ImageBase64, bool? ExpectMultiple);

public record BarcodeResponse
{
    public bool Success { get; init; }
    public List<BarcodeData> Barcodes { get; init; } = new();
}

public record BarcodeData
{
    public string Type { get; init; }
    public string Value { get; init; }
    public double Confidence { get; init; }
    public BarcodePosition Position { get; init; }
}

public record BarcodePosition(int X, int Y, int Width, int Height);

public record ErrorResponse
{
    public bool Success => false;
    public string Error { get; init; }
}
$vbLabelText   $csharpLabel

此端点接受base64编码图像——这是通过HTTP传输图像的标准格式。响应包括条码类型、解码值、置信分数和位置数据。 对于高负荷场景,查看批量条码处理读取速度优化选项。

API如何处理多个条码?

三个不同的条码格式,标记为A B C,展示了可同时在生产环境中处理的QR码、Code128和DataMatrix符号学

IronBarcode在一次调用中处理单个图像中的多个条码,返回结果数组。 响应中的每个条目都包含位置信息,以便客户端应用程序可以在屏幕上突出显示检测到的条码。

浏览器开发者工具网络选项卡显示成功的JSON API响应,包含三个检测到的条码的数组,及完整的元数据,包括类型、值、置信和位置坐标

结构化的JSON响应为客户端应用程序提供了处理和显示条码结果所需的一切,无需额外查找。

如何处理有挑战性的条码图像?

现实世界的条码扫描经常涉及不完美的图像——在角度拍摄的照片,光线不佳或部分破损的条码。 IronBarcode通过其先进的图像处理能力机器学习置信度阈值解决这些情景。

诊断常见扫描问题

在应用校正之前,识别您的问题属于哪个类别。 生产中大多数扫描故障可分为五组:图像质量问题(模糊、噪声、低分辨率)、几何问题(旋转、倾斜、透视变形)、损坏问题(标签撕裂、墨迹模糊)、环境问题(眩光、阴影、不一致的照明)和误诊问题,其中读取器找到一个不存在的条码。

了解类目有助于选择正确的滤镜组合和读取速度,而无需在每个图像上运行不必要的处理。 对于大多数Web应用程序场景,使用AutoRotate = true的起步能够覆盖大部分情况。 仅当第一次扫描无结果时才会升级到ExtremeDetail

下面代码中的多遍方法实现了这种分层策略。 快速第一遍快速处理典型图像,保持常见情况下的平均延迟的低。 详细的第二遍仅在第一遍失败时触发,确保只有在真正需要时才支付额外的处理开销。 这种模式在正常负载下保持您的ASP.NET端点响应性,同时仍然可靠地处理困难的边缘情况。

常见条码扫描问题及其解决方案
问题 症状 解决方案
图像模糊 低置信分数,漏读 应用`SharpenFilter`,增加`ExtremeDetail`速度
条码旋转 条码完全未检测到 启用`AutoRotate = true`
条码损坏 局部读取,值错误 启用错误校正,使用`RemoveFalsePositive`
对比度差 检测不一致 应用`ContrastFilter`和`BrightnessFilter`
性能太慢 上传延迟高 使用`ReadingSpeed.Faster`,启用多线程

实施多遍图像处理

对于有挑战性的图像,分层处理方法提供最佳结果,同时不牺牲简单图像上的性能:

public class AdvancedBarcodeProcessor
{
    private readonly ILogger<AdvancedBarcodeProcessor> _logger;

    public async Task<List<ScannedBarcode>> ProcessChallengingImage(Stream imageStream)
    {
        // First pass -- fast, minimal processing
        var fastOptions = new BarcodeReaderOptions
        {
            Speed = ReadingSpeed.Balanced,
            ExpectMultipleBarcodes = true,
            AutoRotate = false,
            UseConfidenceThreshold = true,
            ConfidenceThreshold = 0.85
        };

        var results = BarcodeReader.Read(imageStream, fastOptions);

        if (!results.Any())
        {
            // Second pass -- aggressive image correction
            imageStream.Position = 0;

            var detailedOptions = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.ExtremeDetail,
                ExpectMultipleBarcodes = true,
                AutoRotate = true,
                RemoveFalsePositive = true,
                UseConfidenceThreshold = true,
                ConfidenceThreshold = 0.6,
                Multithreaded = true,
                ExpectBarcodeTypes = BarcodeEncoding.All,
                ImageFilters = new ImageFilterCollection
                {
                    new SharpenFilter(2.5f),
                    new ContrastFilter(2.0f),
                    new BrightnessFilter(1.2f),
                    new InvertFilter()
                }
            };

            results = BarcodeReader.Read(imageStream, detailedOptions);
            _logger.LogInformation("Second pass detected {Count} barcodes", results.Count());
        }

        return results.Select(r => new ScannedBarcode
        {
            Value = r.Text,
            BarcodeType = r.BarcodeType.ToString(),
            Confidence = r.Confidence,
            RotationAngle = r.RotationAngle,
            PageNumber = r.PageNumber
        }).ToList();
    }
}

public record ScannedBarcode
{
    public string Value { get; init; }
    public string BarcodeType { get; init; }
    public double Confidence { get; init; }
    public float RotationAngle { get; init; }
    public int PageNumber { get; init; }
}
public class AdvancedBarcodeProcessor
{
    private readonly ILogger<AdvancedBarcodeProcessor> _logger;

    public async Task<List<ScannedBarcode>> ProcessChallengingImage(Stream imageStream)
    {
        // First pass -- fast, minimal processing
        var fastOptions = new BarcodeReaderOptions
        {
            Speed = ReadingSpeed.Balanced,
            ExpectMultipleBarcodes = true,
            AutoRotate = false,
            UseConfidenceThreshold = true,
            ConfidenceThreshold = 0.85
        };

        var results = BarcodeReader.Read(imageStream, fastOptions);

        if (!results.Any())
        {
            // Second pass -- aggressive image correction
            imageStream.Position = 0;

            var detailedOptions = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.ExtremeDetail,
                ExpectMultipleBarcodes = true,
                AutoRotate = true,
                RemoveFalsePositive = true,
                UseConfidenceThreshold = true,
                ConfidenceThreshold = 0.6,
                Multithreaded = true,
                ExpectBarcodeTypes = BarcodeEncoding.All,
                ImageFilters = new ImageFilterCollection
                {
                    new SharpenFilter(2.5f),
                    new ContrastFilter(2.0f),
                    new BrightnessFilter(1.2f),
                    new InvertFilter()
                }
            };

            results = BarcodeReader.Read(imageStream, detailedOptions);
            _logger.LogInformation("Second pass detected {Count} barcodes", results.Count());
        }

        return results.Select(r => new ScannedBarcode
        {
            Value = r.Text,
            BarcodeType = r.BarcodeType.ToString(),
            Confidence = r.Confidence,
            RotationAngle = r.RotationAngle,
            PageNumber = r.PageNumber
        }).ToList();
    }
}

public record ScannedBarcode
{
    public string Value { get; init; }
    public string BarcodeType { get; init; }
    public double Confidence { get; init; }
    public float RotationAngle { get; init; }
    public int PageNumber { get; init; }
}
$vbLabelText   $csharpLabel

BarcodeReaderOptions类在扫描的每个方面提供细粒度控制。 设置AutoRotate可以处理在任何角度捕获的图像,而图像滤镜能提高模糊或低对比度条码的清晰度。 有关详细配置,请参见条码阅读器设置示例PDF专用阅读器设置

在处理PDF时,考虑在PDF上加盖条码将条码创建为PDF文档。 对于高负荷处理,启用通过异步和多线程功能来显著提高吞吐量。

添加浏览器兼容性和回退策略

支持不同的浏览器需要渐进增强。 Android和桌面Chrome、Edge和Firefox上的现代浏览器支持用于相机访问的MediaDevices.getUserMedia() API。 iOS上的Safari从版本11开始支持它。 旧版企业浏览器、IE11兼容模式和某些被锁定的公司环境可能完全不支持相机访问,所以您的回退文件上传路径必须始终保持功能。

建议的方法是在运行时使用特征检测而非用户代理嗅探,然后根据情况显示或隐藏相机界面。 从支持摄机的界面开始,并平滑地回退到文件上传:

@* Razor view with progressive enhancement *@
<div class="barcode-scanner-container">
    @* Camera capture -- hidden until JavaScript confirms support *@
    <div id="cameraSection" class="d-none">
        <video id="videoPreview" class="w-100" autoplay></video>
        <button id="captureBtn" class="btn btn-primary mt-2">Capture and Scan</button>
    </div>

    @* File upload -- always available as fallback *@
    <div id="uploadSection">
        <form method="post" enctype="multipart/form-data"
              asp-action="ScanBarcode" asp-controller="Barcode">
            <div class="form-group">
                <label>Upload Barcode Image:</label>
                <input type="file" name="file" accept="image/*,.pdf"
                       class="form-control" required />
            </div>
            <button type="submit" class="btn btn-primary">Upload and Scan</button>
        </form>
    </div>
</div>
@* Razor view with progressive enhancement *@
<div class="barcode-scanner-container">
    @* Camera capture -- hidden until JavaScript confirms support *@
    <div id="cameraSection" class="d-none">
        <video id="videoPreview" class="w-100" autoplay></video>
        <button id="captureBtn" class="btn btn-primary mt-2">Capture and Scan</button>
    </div>

    @* File upload -- always available as fallback *@
    <div id="uploadSection">
        <form method="post" enctype="multipart/form-data"
              asp-action="ScanBarcode" asp-controller="Barcode">
            <div class="form-group">
                <label>Upload Barcode Image:</label>
                <input type="file" name="file" accept="image/*,.pdf"
                       class="form-control" required />
            </div>
            <button type="submit" class="btn btn-primary">Upload and Scan</button>
        </form>
    </div>
</div>
$vbLabelText   $csharpLabel

Blazor集成提供了现代Web应用支持,几乎无需配置,如果您更喜欢基于组件的方法。 有关部署故障排除,请参考运行时复制异常指南

您的下一步是什么?

在ASP.NET中使用IronBarcode进行条码扫描非常简单。 您只需安装一个NuGet包,调用BarcodeReader.Read(),即可在30多种格式中获得可靠的解码结果——包括其他库难以处理的复杂现实图像。

为了继续在这个基础上构建,探索以下资源:

开始使用免费试用许可证在您的ASP.NET应用程序中测试IronBarcode,没有限制。 该试用版包括对所有功能的完全访问,包括多格式检测、图像校正和本指南中显示的REST API模式——以便您可以在承诺生产许可证之前评估您自己的图像性能。 对于需要设备内扫描的.NET MAUI移动应用,请参见.NET MAUI条码扫描器教程,该教程将同一API扩展到iOS和Android目标。

常见问题解答

条形码扫描在 ASP.NET 应用程序中的主要用途是什么?

条形码扫描在 ASP.NET 应用程序中的主要用途是提升库存管理系统、处理活动门票和数字化纸质文件,从而提高效率并减少错误。

IronBarcode 如何在 ASP.NET 中实现条形码扫描?

IronBarcode 通过提供可靠且高效的组件简化了 ASP.NET 中的条形码扫描过程,这些组件可以轻松集成到 Web 应用程序中,使开发人员能够快速实现扫描功能。

IronBarcode 可以扫描哪些类型的条形码?

IronBarcode 支持扫描各种条形码格式,包括传统的线性条形码和现代的二维条形码,确保与多种应用兼容。

IronBarcode 可以处理文件处理中的条形码扫描吗?

是的,IronBarcode 非常适合文件处理工作流程,其中可以通过扫描嵌入的条形码来数字化和组织纸质文件。

IronBarcode 适合用于库存管理系统吗?

IronBarcode 是库存管理系统的理想选择,因为它可以通过扫描条形码实现高效的产品跟踪,从而简化操作并减少错误。

集成 IronBarcode 如何改善活动门票处理?

通过集成 IronBarcode,活动门票处理变得无缝,因为它允许快速扫描门票条形码,从而在活动中实现快速准确的入场管理。

在 ASP.NET 项目中使用 IronBarcode 有哪些优势?

在 ASP.NET 项目中使用 IronBarcode 提供了多种优势,包括易于集成、支持多种条形码格式以及增强的应用程序性能,从而为条形码扫描需求提供了一个强大的解决方案。

IronBarcode 需要广泛的编码知识才能实现吗?

不,IronBarcode 被设计为对开发人员友好,使得在 ASP.NET 应用程序中实现条形码扫描功能变得简单,即使具有最少的编码知识。

IronBarcode 可以用于移动 Web 应用程序吗?

是的,IronBarcode 可以集成到移动 Web 应用程序中,允许随时随地进行条形码扫描,增强 ASP.NET 项目的多功能性。

Jordi Bardia
软件工程师
Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。

钢铁支援团队

我们每周 5 天,每天 24 小时在线。
聊天
电子邮件
打电话给我