如何将XML发布到asp.net核心2.0 web api?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (59)

试图将XML发布到asp.net核心2:

$.ajax({
    type: "POST",
    url: 'api/Test',
    data: "<test>hello<test>",
    contentType: "application/xml",
    success: function (response) { alert(response); },
});

应该如何编写动作,以便接受xml作为参数?

  • IActionResult Post([FromBody]string xml) - > xml为空
  • IActionResult Post([FromBody]XElement xml) - > xml为空
  • IActionResult Post(XElement xml) - > InvalidOperationException:无法创建类型为“System.Xml.Linq.XElement”的实例。模型绑定的复杂类型不能是抽象或值类型,并且必须具有无参数的构造函数。
  • IActionResult Post(string xml) - > xml为空

在Startup.ConfigureServices:

services.AddMvc()
    .AddXmlSerializerFormatters();

如何编写控制器以便它接受XML作为参数?我知道可以从HttpContext.Request中读取它,但我希望它是参数

提问于
用户回答回答于

创建了自定义的InputFormatter

public class XDocumentInputFormatter : InputFormatter, IInputFormatter, IApiRequestFormatMetadataProvider
{
    public XDocumentInputFormatter()
    {
        SupportedMediaTypes.Add("application/xml");
    }

    protected override bool CanReadType(Type type)
    {
        if (type.IsAssignableFrom(typeof(XDocument))) return true;
        return base.CanReadType(type);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        var xmlDoc = await XDocument.LoadAsync(context.HttpContext.Request.Body, LoadOptions.None, CancellationToken.None);
        return InputFormatterResult.Success(xmlDoc);
    }
}

在startup.cs中注册XDocumentInputFormatter

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options => options.InputFormatters.Insert(0, new XDocumentInputFormatter()));
}
用户回答回答于

应该使用StreamReader,以便支持多种编码。使用UTF-8,UTF-16和ASCI声明标头测试我的解决方案。

从XDocumentInputFormatter更改方法:

public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
    var xmlDoc = await XDocument.LoadAsync(context.HttpContext.Request.Body, LoadOptions.None, CancellationToken.None);
    return InputFormatterResult.Success(xmlDoc);
}

到下面

public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) {
        // Use StreamReader to convert any encoding to UTF-16 (default C# and sql Server).
        using (var streamReader = new StreamReader(context.HttpContext.Request.Body)) {
            var xmlDoc = await XDocument.LoadAsync(streamReader, LoadOptions.None, CancellationToken.None);
            return InputFormatterResult.Success(xmlDoc);
        }
    }

扫码关注云+社区

领取腾讯云代金券