繁体   English   中英

XML 反序列化从一个 webAPI 而不是另一个 webAPI 失败

[英]XML deserialization failing from one webAPI and not another

我的环境:Visual Studio 2010

我有 2 个 C# webAPI 项目,它们将数据返回到 VB 客户端项目。

API 项目 #1:OrchardsAPI - 完美返回大量数据。

API 项目 #2:aspnetAPI - 访问我的 SQL 服务器上的 Microsoft aspnetdb 数据库。 在客户端上反序列化时引发异常。

当我直接从浏览器查询 API 项目时,以下是每个响应的第一行。 API#1 返回我果园中使用的栽培品种列表。 请注意 xmlns 值。

API #1:

<ArrayOfCultivarEntity xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

API #2:

<ArrayOfaspnet_RoleEntity xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/aspnetEntities">

当直接从浏览器访问时,将显示一个有效的 xml 文件,其中包含来自每个 API 的记录。 但是,当我从客户那里获得数据请求时,我得到一个异常说明:

InnerException  {"<ArrayOfaspnet_RoleEntity xmlns='http://schemas.datacontract.org/2004/07/aspnetEntities'> was not expected."}

我的客户端中的相关代码是:

   Public Function GetAllRoles() As List(Of aspnetEntities.aspnet_RoleEntity)
        Dim _entities As New List(Of aspnet_RoleEntity)
        Try
            url = "role/byAppName/OrchardAutomation"
            responseMessage = client.GetAsync(url).Result
            If responseMessage.IsSuccessStatusCode = True Then
                _entities = New Xml.Serialization.XmlSerializer(_entities.GetType).Deserialize(responseMessage.Content.ReadAsStreamAsync.Result)
                Return _entities
            Else
                ProcessClientError(responseMessage.Content.ReadAsStringAsync.Result)
                Return Nothing
            End If
        Catch ex As Exception
            ProcessClientException(ex)
            Return Nothing
        End Try
    End Function

我在 API 项目中搜索了所有“xmlns”实例,它们都是相同的。 一定有什么我错过了。 任何提示都非常感谢。

感谢以下链接解决:[https://docs.microsoft.com/de-de/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization#xml_media_type_formatter]

原来我的 API #1 在 global.asax 文件中有以下代码:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml")));
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

上述链接指出,datacontract 序列化程序是默认的,必须添加代码才能切换到 xml 格式化程序:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;

我把它放在我的 controller 的初始化部分。 这解决了问题。 然后我查看了 API#1 中的 global.asax 并在 app_start 方法中找到了 3 行。 我将它们插入 API#2 的 app_start 中,从单个 controller 的初始化中删除了“var xml”行,项目继续完美运行。

希望这对其他人有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM