【问题标题】:How to add variables inside a StringContent("")如何在 StringContent("") 中添加变量
【发布时间】:2018-10-05 09:00:04
【问题描述】:

早安,

我对编程和尝试使用 API 真的很陌生。

我从 API 文档中看到了这个例子

using (var content = new StringContent("{  \"orderNumber\": \"TEST-ORDER-API-DOCS\",  \"orderKey\": \"0f6bec18-3e89-4881-83aa-f392d84f4c74\",  \"orderDate\": \"2015-06-29T08:46:27.0000000\",  \"paymentDate\": \"2015-06-29T08:46:27.0000000\",  \"shipByDate\": \"2015-07-05T00:00:00.0000000\",  \"orderStatus\": \"awaiting_shipment\",  \"customerId\": 37701499,  \"customerUsername\": \"headhoncho@whitehouse.gov\",  \"customerEmail\": \"headhoncho@whitehouse.gov\",  \"billTo\": {    \"name\": \"The President\",    \"company\": null,    \"street1\": null,    \"street2\": null,    \"street3\": null,    \"city\": null,    \"state\": null,    \"postalCode\": null,    \"country\": null,    \"phone\": null,    \"residential\": null  },  \"shipTo\": {    \"name\": \"The President\",    \"company\": \"US Govt\",    \"street1\": \"1600 Pennsylvania Ave\",    \"street2\": \"Oval Office\",    \"street3\": null,    \"city\": \"Washington\",    \"state\": \"DC\",    \"postalCode\": \"20500\",    \"country\": \"US\",    \"phone\": \"555-555-5555\",    \"residential\": true  },  \"items\": [    {      \"lineItemKey\": \"vd08-MSLbtx\",      \"sku\": \"ABC123\",      \"name\": \"Test item #1\",      \"imageUrl\": null,      \"weight\": {        \"value\": 24,        \"units\": \"ounces\"      },      \"quantity\": 2,      \"unitPrice\": 99.99,      \"taxAmount\": 2.5,      \"shippingAmount\": 5,      \"warehouseLocation\": \"Aisle 1, Bin 7\",      \"options\": [        {          \"name\": \"Size\",          \"value\": \"Large\"        }      ],      \"productId\": 123456,      \"fulfillmentSku\": null,      \"adjustment\": false,      \"upc\": \"32-65-98\"    },    {      \"lineItemKey\": null,      \"sku\": \"DISCOUNT CODE\",      \"name\": \"10% OFF\",      \"imageUrl\": null,      \"weight\": {        \"value\": 0,        \"units\": \"ounces\"      },      \"quantity\": 1,      \"unitPrice\": -20.55,      \"taxAmount\": null,      \"shippingAmount\": null,      \"warehouseLocation\": null,      \"options\": [],      \"productId\": 123456,      \"fulfillmentSku\": \"SKU-Discount\",      \"adjustment\": true,      \"upc\": null    }  ],  \"amountPaid\": 218.73,  \"taxAmount\": 5,  \"shippingAmount\": 10,  \"customerNotes\": \"Thanks for ordering!\",  \"internalNotes\": \"Customer called and would like to upgrade shipping\",  \"gift\": true,  \"giftMessage\": \"Thank you!\",  \"paymentMethod\": \"Credit Card\",  \"requestedShippingService\": \"Priority Mail\",  \"carrierCode\": \"fedex\",  \"serviceCode\": \"fedex_2day\",  \"packageCode\": \"package\",  \"confirmation\": \"delivery\",  \"shipDate\": \"2015-07-02\",  \"weight\": {    \"value\": 25,    \"units\": \"ounces\"  },  \"dimensions\": {    \"units\": \"inches\",    \"length\": 7,    \"width\": 5,    \"height\": 6  },  \"insuranceOptions\": {    \"provider\": \"carrier\",    \"insureShipment\": true,    \"insuredValue\": 200  },  \"internationalOptions\": {    \"contents\": null,    \"customsItems\": null  },  \"advancedOptions\": {    \"warehouseId\": 98765,    \"nonMachinable\": false,    \"saturdayDelivery\": false,    \"containsAlcohol\": false,    \"mergedOrSplit\": false,    \"mergedIds\": [],    \"parentId\": null,    \"storeId\": 12345,    \"customField1\": \"Custom data that you can add to an order. See Custom Field #2 & #3 for more info!\",    \"customField2\": \"Per UI settings, this information can appear on some carrier's shipping labels. See link below\",    \"customField3\": \"https://help.shipstation.com/hc/en-us/articles/206639957\",    \"source\": \"Webstore\",    \"billToParty\": null,    \"billToAccount\": null,    \"billToPostalCode\": null,    \"billToCountryCode\": null  }}", System.Text.Encoding.Default, "application/json"))

这确实是一个愚蠢的问题,但我想做的是向这个字符串内容添加变量。问题是我不太明白如何阅读或如何格式化这个字符串(特别是“\”)。如果我需要添加“\”,我通常会在字符串中添加@,所以我不确定“\”是否应该包含在某些部分的字符串中,或​​者在此示例中用于连接。

有人可以帮助我如何向这个字符串内容添加变量吗?

感谢您的帮助!

【问题讨论】:

标签: c# api


【解决方案1】:

来自 MSDN

基于字符串提供 HTTP 内容。

StringContent 的最基本用途是在访问任何 API 时向服务器发送数据。

这里我举一个系统中Login API的简单例子。

// Following is the key value pairs (data) which we need to send to server via API.
Dictionary<string, string> jsonValues = new Dictionary<string, string>();
jsonValues.Add("username", "testuser");
jsonValues.Add("password", "XXXXXXXXXX"); // better to encrypt passwod before sending to API.

HttpClient client = new HttpClient();

// Used Newtonsoft.Json library to convert object to json string. It is available in Nuget package.
StringContent sc = new StringContent(JsonConvert.SerializeObject(jsonValues), UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(webAddress, sc);

string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("Result: " + content);

查看this SO 帖子,了解其他用户的其他解释。

【讨论】:

    【解决方案2】:

    您不能在您的内容中使用“\”字符,您必须将您的内容转换为Base64 流并在目的地将其恢复为您的计划内容,您可以在中找到完整的解释和代码这个答案:

    https://stackoverflow.com/a/13938317/4189817

    【讨论】:

      【解决方案3】:

      要回答您的其他问题, 字符串前的@表示它是字符串文字,您输入的所有内容都将逐字记录在字符串中。

      在字符串变量中,有些字符必须“转义”,\是转义字符。

      要获得双引号,您必须输入 \"

      要放入单个 \,请键入两个反斜杠

      换行符是\n

      制表符是\t

      【讨论】:

        【解决方案4】:
        StringContent sc = new StringContent("{\"title\":\"" + yourStringVariable + "\"}");
        

        【讨论】:

        • 虽然这段代码可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因
        • 在发布代码示例时也要使用正确的格式。
        猜你喜欢
        • 2020-12-03
        • 2020-02-05
        • 2017-09-11
        • 2022-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多