You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core Web API中读取application/xml请求体为字符串?

解决ASP.NET Core Web API读取application/xml为字符串的问题

方法一:直接读取请求体原始内容

不需要使用[FromBody]参数,直接通过Request.Body获取XML原始字符串,这种方式跳过框架模型绑定流程,适合单个接口的场景:

[HttpPost]
public async Task<IActionResult> UpdateStatus()
{
    using var streamReader = new StreamReader(Request.Body);
    string xmlContent = await streamReader.ReadToEndAsync();

    // 执行自定义检查逻辑
    if (string.IsNullOrWhiteSpace(xmlContent))
    {
        return BadRequest("XML内容不能为空");
    }

    // 后续XML转换处理
    // ...

    return Ok();
}

方法二:自定义输入格式化器(支持[FromBody]绑定)

如果多个接口需要将application/xml请求直接绑定到string参数,可以自定义输入格式化器,让框架适配该绑定规则:

1. 实现自定义输入格式化器

public class XmlStringInputFormatter : TextInputFormatter
{
    public XmlStringInputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }

    protected override bool CanReadType(Type type)
    {
        // 仅处理string类型的参数绑定
        return type == typeof(string);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
    {
        using var streamReader = new StreamReader(context.HttpContext.Request.Body, encoding);
        string xmlContent = await streamReader.ReadToEndAsync();
        return await InputFormatterResult.SuccessAsync(xmlContent);
    }
}

2. 注册格式化器

在Program.cs(.NET 6+)或Startup.cs中,将自定义格式化器添加到服务配置:

builder.Services.AddControllers(options =>
{
    // 插入到格式化器列表最前面,确保优先被使用
    options.InputFormatters.Insert(0, new XmlStringInputFormatter());
});

3. 使用[FromBody]绑定string参数

控制器方法可正常使用[FromBody],框架会自动将application/xml请求内容绑定到string参数:

[HttpPost]
public async Task<IActionResult> UpdateStatus([FromBody] string msg)
{
    // 自定义检查逻辑
    if (string.IsNullOrWhiteSpace(msg))
    {
        return BadRequest("XML内容不能为空");
    }

    // 后续XML转换处理
    // ...

    return Ok();
}

内容的提问来源于stack exchange,提问作者Patola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:01:11