在.net核心WebAPI中获取xml字符串或反序列化对象

时间:2016-11-01 10:06:18

标签: asp.net-web-api

.net核心中的WebAPI可以优雅地处理Json请求,但它似乎无法本机处理XML内容类型?

我做了一些搜索,只获得了有关此内容的帖子http://www.strathweb.com/2015/04/asp-net-mvc-6-formatters-xml-browser-requests/

然而,我尝试如下,不成功

services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
    })
    .AddMvcOptions(options =>
    {
        //var jsonFormatter = options.InputFormatters.First(o => o.GetType() == typeof(JsonInputFormatter));
        //if (jsonFormatter != null) { options.InputFormatters.Remove(jsonFormatter); }
        options.InputFormatters.Add(new XmlSerializerInputFormatter());
        options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
        options.RespectBrowserAcceptHeader = true; // false by default
        options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter(
            new System.Xml.XmlWriterSettings
            {
                ConformanceLevel = System.Xml.ConformanceLevel.Auto,
                WriteEndDocumentOnClose = true
            }
            ));
        var a = options.FormatterMappings.GetMediaTypeMappingForFormat("text/xml");
    })
    .AddXmlSerializerFormatters()
    .AddXmlDataContractSerializerFormatters()
    ;

以下是我的控制器操作

// POST api/values
[HttpPost("Order")]
public string OrderRetrievea([FromBody] OrderRequest request)
{
}

Content-type设置为text / xml。

Xml请求:

<?xml version="1.0"?>
<OrderRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.myco.org/ns">
   ....
</OrderRequest>

它(请求)始终为空。

0 个答案:

没有答案