IRONSOFTWAREHOME
USING IRONBARCODE

How to Print Barcode in ASP.NET in C#

Curtis Chau
Curtis Chau
Updated: 2026年6月28日

本文将演示如何在ASP.NET Web应用程序中使用C#打印条形码图像。 在这个示例中将使用MVC框架,但您也可以根据需要使用ASP.NET Web Forms、Windows Forms或Web API。

对ASP.NET MVC框架的基本了解将帮助您更好地理解这篇文章。


创建MVC项目

打开Microsoft Visual Studio。 点击创建新项目 > 从模板中选择ASP.NET Web应用程序 > 按下一步 > 为项目命名 > 按下一步 > 选择MVC > 点击创建按钮。 项目创建如下所示。

如何在ASP.NET中打印条形码,图1:创建一个新的ASP.NET项目 创建一个新的ASP.NET项目

添加模型

右键点击Models文件夹 > 添加 > 类...

如何在ASP.NET中打印条形码,图2:导航到添加类对话框 导航至添加类对话框

将出现一个新窗口。 将您的类命名为BarcodeModel

在模型类中编写以下代码。

using System.ComponentModel.DataAnnotations;

public class BarcodeModel
{
    [Display(Name ="Barcode File Name")]
    public string FileName { get; set; }

    [Display(Name = "Barcode Content")]
    public string BarcodeContent { get; set; }
}

FileName将用于从用户获取条形码图像名称。 BarcodeContent用于获取条形码的内容。

添加控制器

接下来,将Controller添加到项目中。 它将使用MVC模型与Model进行通信。 生成条形码的代码仅由两到三行组成。 因此,不需要单独的类; 而是将代码添加到控制器中。

要添加控制器,右键点击Controllers文件夹 > 添加 > 控制器。 将出现一个新窗口。 选择空的MVC 5控制器。 点击添加按钮。 一个新框将出现。

如何在ASP.NET中打印条形码,图3:添加控制器对话框 添加控制器对话框

输入您的控制器名称,例如BarcodeController。 点击添加按钮。 一个新的控制器将被生成。

下一步是安装条形码库。

安装条形码库

IronBarcode库被推荐作为生成条形码的第三方库。 它对开发免费,并提供多种功能以自定义条形码,例如在条形码图像中添加徽标、在条形码上方或下方添加值、在条形码上方或下方添加注释、调整条形码尺寸、将条形码保存为多种图像格式等。想了解更多,请点击这里。

进入包管理器控制台。 输入以下命令并按回车。

PM > Install-Package BarCode

该命令将在项目中安装IronBarcode库。

生成条形码

接下来,将以下示例代码添加到控制器中。

using System.IO;
using System.Linq;
using System.Web.Mvc;
using IronBarCode;

public class BarcodeController : Controller
{
    [HttpPost]
    public ActionResult CreateBarcode(BarcodeModel model)
    {
        try
        {
            // Create a barcode with the specified content and encoding
            var MyBarCode = BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);

            // Define the path where the barcode image will be saved
            string path = Server.MapPath("~/Files/");
            string filepath = Path.Combine(path, model.FileName);

            // Add the barcode value text above the barcode
            MyBarCode.AddBarcodeValueTextAboveBarcode();

            // Save the generated barcode as a JPEG file
            MyBarCode.SaveAsJpeg(filepath);

            // Retrieve the first file from the directory as a sample image
            string image = Directory.GetFiles(path).FirstOrDefault();

            // Pass the image path to the view
            ViewBag.FileName = image;
            return View();
        }
        catch
        {
            // Handle any exceptions that occur
            return View();
        }
    }
}
  • try-catch用于捕获任何运行时异常。
  • BarcodeWriter类提供,接受两个参数:条形码内容和编码方案。 此外,它还接受包括最大高度、最大宽度等在内的11个可选参数。
  • Server.MapPath功能用于映射生成的条形码图像将被保存的路径。 Path.Combine方法将合并路径和条形码图像名称。
  • AddBarcodeValueTextAboveBarcode功能将添加条形码值。 IronBarcode提供其他条形码设置,如color等。 您可以探索并使用各种参数。
  • SaveAsJpeg功能将路径作为参数,并将生成的条形码保存在该特定路径下。
  • Directory.GetFiles方法将获取新生成的条形码图像。
  • ViewBag.FileName用于将条形码图像的路径发送到视图以显示生成的条形码图像。

可以通过将编码方案从QRCode以相同方式生成QR码。

添加视图

下一步是通过添加新视图为此ASP.NET Web应用程序提供客户端界面。 右键点击控制器方法的名称并单击"添加视图"按钮。

如何在ASP.NET中打印条形码,图4:导航到添加视图对话框 导航至添加视图对话框

将出现一个新窗口。 选择MVC 5视图,并点击添加按钮。

一个新的提示框将出现,如下所示。

如何在ASP.NET中打印条形码,图5:添加视图对话框 添加视图对话框

命名您的视图并点击添加按钮。 将创建一个新的.cshtml文件。

在新生成的视图中添加以下代码。

@model GenerateBarcodeMVC.Models.BarcodeModel

@{
    ViewBag.DisplayBarcode = false;
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>GenerateBarcode</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BarcodeContent, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BarcodeContent, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BarcodeContent, "", new { @class = "text-danger" })
            </div>
        </div>
        
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <img src="~/Files/@Path.GetFileName(ViewBag.FileName)" alt="Barcode" />
            </div>
        </div>
        
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
HTML

接下来,右键点击视图内部,并点击运行到浏览器按钮。

输出

如何在ASP.NET中打印条形码,图6:运行Web应用程序以显示创建表单 运行Web应用程序以显示创建表单

输入您的条形码图像名称和条形码内容,如下所示:

如何在ASP.NET中打印条形码,图7:输入您的条形码内容 输入您的条形码内容

点击创建按钮。 条形码图像将被生成并显示在屏幕上,如下所示。

如何在ASP.NET中打印条形码,图8:从URL生成条形码 从URL生成条形码

摘要

本教程演示了如何结合使用MVC框架在ASP.NET中用C#生成条形码。 Microsoft Visual Studio被用作IDE。IronPDF是免费的第三方库,兼容所有.NET Framework版本,包括新发布的版本。 IronBarcode速度快,并为处理条形码提供多种功能。 它还可以通过指定不同类型生成QR码

还有许多其他实用库,如用于处理PDF文档的IronPDF,处理Excel文档的IronXL和处理OCR的IronOCR。 目前,您只需购买两个价格即可获得全部五个库,通过购买完整的Iron Suite。访问我们的许可页面了解更多详情。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

...
阅读更多

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户