我在 asp net core 2.2 上的应用程序中通过 POST 多部分请求收到 Xml 文档当我尝试将文档反序列化为 Dto 对象时,出现异常,指示包含俄语字符的字符串中的编码错误。
{System.InvalidOperationException: There is an error in XML document (8, 15). ---> System.Xml.XmlException: Invalid character in the given encoding. Line 8, position 15.
<StartStation>Красноярск</StartStation>
如果克拉斯诺亚尔斯克被克拉斯诺亚尔斯克取代,那么一切都会奏效。
XML 标头中的编码是“utf-8”,不能更改,因为 PHP 中的许多客户端通常会接收文件。
<?xml version="1.0" encoding="utf-8"?>
<tlist>
<t>
<ScheduleId>20905</ScheduleId>
<TrainNumber>6337</TrainNumber>
<TrainType></TrainType>
<StartStation>Красноярск</StartStation>
</t>
</tlist>
[Serializable]
[XmlRoot("tlist")]
public class AdInputType4XmlDtoContainer
{
[XmlElement("t")]
public List<AdInputType4XmlDto> Trains { get; set; } = new List<AdInputType4XmlDto>();
}
[Serializable]
public class AdInputType4XmlDto
{
public int Id { get; set; }
public int ScheduleId { get; set; }
public int TrnId { get; set; }
public string TrainNumber { get; set; }
public string TrainType { get; set; }
public string DirectionStation { get; set; }
public string StartStation { get; set; }
}
[HttpPost("SendDataXmlMultipart4Devices")]
public async Task<IActionResult> SendDataXmlMultipart4Devices([FromForm] IFormFile username) )
{
var xmlFile = username;
try
{
if (username.Length > 0)
{
using (var memoryStream = new MemoryStream())
{
await xmlFile.CopyToAsync(memoryStream);
var formatter = new XmlSerializer(typeof(AdInputType4XmlDtoContainer));
memoryStream.Position = 0;
var adInputType4XmlList = (AdInputType4XmlDtoContainer)formatter.Deserialize(memoryStream); //!!!! ИСКЛЮЧЕНИЕ
}
}
}
catch (Exception ex)
{
_logger.Error(ex, "Ошибка в InputDataController/SendDataXmlMultipart4Devices");
throw;
}
}
通过编码为“Windows-1251”的 StreamReader 读取 memoryStream。
PS 默认情况下,net core 本身并没有找到这个编码,我只好在 Main 方法中调用它来注册整个 WebApi 的编码。