【问题标题】:Decoding JSON command line arguments fails after build but succeeds during debug构建后解码 JSON 命令行参数失败,但在调试期间成功
【发布时间】:2021-06-09 14:46:03
【问题描述】:

我正在构建一个 C# 应用程序来处理我的 Web 应用程序中使用的自定义协议。

链接如下:

<a href="zebra-wp://%7B%22barcode%22%3A63%2C%22name%22%3A%22Food%20Fun%20-%20Magnetic%20Multicultural%20set%22%7D">Print</a>

这些是使用 Windows 注册表中的处理程序处理的(URL:zebra-wp 协议):

"C:\Program Files (x86)\[My App Name]\[My App].exe" "%1"

我在我的应用程序中运行以下代码:

class LabelData
    {
        public string name;
        public string barcode;
    }

    static class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0 && args[0].StartsWith("zebra-wp://"))
            {

                // retrieve data from argument
                string argData = args[0].Remove(0, 11);

                string decodedJson = "";
                try
                {
                    // Undo URL Encoding
                    decodedJson = WebUtility.UrlDecode(argData);
                }
                catch (Exception ex)
                {
                    string msg = "Couldn't print label, failed to decode data.";
                    msg += "\nData: " + argData;
                    msg += "Error: " + ex.Message;
                    MessageBox.Show(msg);
                    Application.Exit();
                }

                // Unpack JSON string
                LabelData decodedData = new LabelData();
                try
                {
                    decodedData = JsonConvert.DeserializeObject<LabelData>(decodedJson);
                }
                catch (Exception ex)
                {
                    string msg = "Couldn't print label, failed to unpack data.";
                    msg += "\nData: " + decodedJson;
                    msg += "Error: " + ex.Message;
                    MessageBox.Show(msg);
                    Application.Exit();
                }

                // Do things with object

当我调试应用程序时,我将链接 URL 输入到“命令行参数”启动选项中。 程序按预期运行,成功解码 JSON 数据。

当我构建和安装时,JsonConvert.DeserializeObject 函数给了我以下错误:

Data: {"barcode":"000063","name":"Food Fun - Magnetic Multicultural set"}
Error: Unexpected end while parsing comment. Path '', line 1, position 68.

VS 如何在调试中使用命令行参数启动应用程序有什么不同吗? 有没有办法使用与单击 URL 时相同的命令行参数来调试应用程序?

【问题讨论】:

  • 您可以通过项目属性-->调试-->命令行参数提供参数
  • @HimBromBeere 是的,我正在这样做,当我在那里提供它们时它可以工作,但在安装后运行时不起作用

标签: c# json json.net command-line-arguments


【解决方案1】:

我发现了这个问题,显然在将 URI 传递给自定义协议处理程序时,Windows 会在 URI 中添加一个尾部正斜杠,在代码中检查并删除它可以解决问题。

【讨论】:

    猜你喜欢
    • 2011-10-02
    • 1970-01-01
    • 2021-12-24
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    相关资源
    最近更新 更多