You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在.NET4.6.1的C#中如何转义三引号用于GraphQL查询?

解决.NET 4.6.1中GraphQL查询的三引号转义问题

由于.NET 4.6.1不支持C# 11的原始字符串特性,要构造Shopify bulkOperationRunQuery所需的三引号包裹的查询内容,可通过以下几种方法实现:

方法一:逐字字符串转义双引号

在C#逐字字符串(以@开头)中,单个双引号需要用两个双引号""转义。要生成""",只需写六个连续双引号""""""即可:

var request = new GraphQLRequest
{
    Query = @"mutation {
        bulkOperationRunQuery(
            query: """"""
            {
                products {
                    edges {
                        node {
                            id
                            title
                        }
                    }
                }
            }
            """"""
        ) {
            bulkOperation {
                id
                status
            }
            userErrors {
                field
                message
            }
        }
    }"
};

方法二:普通字符串转义双引号

使用普通字符串时,用\"转义单个双引号,三个双引号对应\"\"\",同时手动处理换行:

var request = new GraphQLRequest
{
    Query = "mutation {\n" +
            "    bulkOperationRunQuery(\n" +
            "        query: \"\\\"\\\"\\\"\"\n" +
            "        {\n" +
            "            products {\n" +
            "                edges {\n" +
            "                    node {\n" +
            "                        id\n" +
            "                        title\n" +
            "                    }\n" +
            "                }\n" +
            "            }\n" +
            "        }\n" +
            "        \"\\\"\\\"\\\"\"\n" +
            "    ) {\n" +
            "        bulkOperation {\n" +
            "            id\n" +
            "            status\n" +
            "        }\n" +
            "        userErrors {\n" +
            "            field\n" +
            "            message\n" +
            "        }\n" +
            "    }\n" +
            "}"
};

方法三:拆分字符串拼接(可读性最优)

将三引号和内部查询拆分为独立变量,再通过string.Format拼接,避免大量转义字符:

var tripleQuotes = "\"\"\"";
var innerProductQuery = @"
{
    products {
        edges {
            node {
                id
                title
            }
        }
    }
}";

var request = new GraphQLRequest
{
    Query = string.Format(@"mutation {{
        bulkOperationRunQuery(
            query: {0}
            {1}
            {0}
        ) {{
            bulkOperation {{
                id
                status
            }}
            userErrors {{
                field
                message
            }}
        }}
    }}", tripleQuotes, innerProductQuery)
};

以上三种方法都能正确生成符合Shopify要求的GraphQL查询字符串,可根据代码可读性需求选择。

内容的提问来源于stack exchange,提问作者Rivka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 21:25:06