0

我正在使用AWS .NET-SDK通过AWS SNS 服务发送 SMS 消息。到现在为止还挺好; 但是当我使用换行符时,我会?在 SMS 中的换行符开始之前看到这个字符。在该字符之后,按预期添加换行符。?没有这个角色有没有可能换行?

我也试过以下:

  • StringBuilder.AppendLine,
  • "\\n",
  • "\\r\\n",
  • @"\n",
  • @"\r\n",
  • Environment.NewLine

并将字符串编码为 UTF-8。

不起作用的示例:

// Create message string
var sb = new StringBuilder();
sb.AppendLine("Line1.");
sb.Append("Line2.\\n");
sb.AppendLine(Environment.NewLine);
sb.Append(@"Line4\n");

// Encode into UTF-8
var utf8 = UTF8Encoding.UTF8;
var stringBytes = Encoding.Default.GetBytes(sb.ToString());
var decodedString = utf8.GetString(stringBytes);
var message = decodedString;

// Create request
var publishRequest = new PublishRequest
{
    PhoneNumber = "+491234567890",
    Message = message,
    Subject = "subject",
    MessageAttributes = "Promotional"
};

// Send SMS
var response = await snsClient.PublishAsync("topic", message, "subject");
4

1 回答 1

0

只需删除对字符串进行编码的所有尝试。.NET 字符串是 Unicode,特别是 UTF16。PublishAsync需要一个 .NET 字符串,而不是 UTF8 字节。

至于为什么会出现这个错误,这是因为代码使用本地机器的代码页将字符串转换为字节,然后尝试读取这些字节,就好像它们是 UTF8 一样,但它们不是 - 使用 UTF8 作为系统代码页是一个 beta 功能在 Windows 10 上,它破坏了许多应用程序。

SMS 的换行符是\n. 除非您在 Linux 上使用 .NET Core,否则Environment.NewLine返回。StringBuilder.AppendLine使用所以你不能使用它。\r\nEnvironment.NewLine

您只需要 String.Join 即可将多行组合成一条消息:

var message=String.Join("\n",lines);

如果您需要使用 StringBuilder,请使用AppendFormat在末尾附加一行\n字符,例如:

builder.AppendFormat("{0}\n",line);

更新

我能够使用以下代码发送包含换行符的短信:

var region = Amazon.RegionEndpoint.EUWest1;
var  snsClient = new AmazonSimpleNotificationServiceClient(region);

var sb = new StringBuilder()
                .Append("Line1.\n")
                .Append("Line2.\n")
                .Append("Line4\n");
var message = sb.ToString();

// Create request
var publishRequest = new PublishRequest
{
    PhoneNumber = phone,
    Message = message,                
};

// Send SMS
var response = await snsClient.PublishAsync(publishRequest);

我收到的消息包含:

Line1.
Line2.
Line4.

我决定变得花哨并将最后一行更改为:

.Append("Line4ΑΒΓ£§¶\n");

我也收到了这个文本没有问题

于 2019-08-08T14:48:40.473 回答