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

如何在ASP.NET Web API的Post方法中同时接收JSON和XML请求

解决ASP.NET Web API Post接口同时支持JSON和XML请求的问题

你的代码问题所在

你不能在同一个Action方法中使用两个[FromBody]参数,ASP.NET Core不支持这种写法——请求体是只读流,只能被绑定解析一次,多个[FromBody]会直接导致绑定失败。

方案一:使用强类型模型(推荐)

这种方式更符合Web API的设计规范,同时自动处理JSON和XML的序列化/反序列化。

  1. 定义匹配请求结构的实体类
    根据你的JSON和XML请求结构,创建对应的实体类,确保字段名称与请求中的键/节点名一致:
public class StudentRegistrationRequest
{
    public string StudentName { get; set; }
    public int Grade { get; set; }
    // 添加其他需要的字段,与你的JSON/XML结构对应
}
  1. 配置XML格式化器
    ASP.NET Core Web API默认只启用JSON格式化器,需要手动添加XML支持。在Program.cs中修改服务配置:
var builder = WebApplication.CreateBuilder(args);

// 添加控制器并同时启用JSON和XML格式化器
builder.Services.AddControllers()
    .AddXmlSerializerFormatters() // 基于XmlSerializer的XML支持
    .AddXmlDataContractSerializerFormatters(); // 可选,基于DataContractSerializer的XML支持

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
  1. 修改Action方法
    用定义好的实体类作为唯一的[FromBody]参数:
[HttpPost]
[Route("Patient/$gpc.registerstudent")]       
[SwaggerOperation(Summary = "Register student")]
public async Task<IActionResult> Registerstudent([FromBody] StudentRegistrationRequest request)
{
    // 这里处理你的注册逻辑,request会自动根据请求的Content-Type(application/json或application/xml)完成解析
    if (request == null)
    {
        return BadRequest("请求格式错误");
    }
    
    // 业务逻辑示例
    await _studentService.RegisterAsync(request);
    return Ok("注册成功");
}

方案二:手动读取并解析请求体(无强类型场景)

如果不想定义实体类,可以直接读取请求体,根据Content-Type判断格式后手动解析:

[HttpPost]
[Route("Patient/$gpc.registerstudent")]       
[SwaggerOperation(Summary = "Register student")]
public async Task<IActionResult> Registerstudent()
{
    var contentType = Request.ContentType?.ToLower();
    if (contentType == null)
    {
        return BadRequest("缺少Content-Type头");
    }

    // 读取请求体内容
    var requestBody = await new StreamReader(Request.Body).ReadToEndAsync();

    if (contentType.Contains("application/json"))
    {
        // 解析JSON
        var jsonParams = JObject.Parse(requestBody);
        var studentName = jsonParams["StudentName"]?.ToString();
        var grade = jsonParams["Grade"]?.ToObject<int>();
        // 处理JSON请求逻辑
    }
    else if (contentType.Contains("application/xml"))
    {
        // 解析XML
        var xmlParams = XElement.Parse(requestBody);
        var studentName = xmlParams.Element("StudentName")?.Value;
        var grade = int.TryParse(xmlParams.Element("Grade")?.Value, out var g) ? g : 0;
        // 处理XML请求逻辑
    }
    else
    {
        return BadRequest("不支持的请求格式,请使用application/json或application/xml");
    }

    return Ok("注册成功");
}

测试注意事项

发送请求时,需要正确设置Content-Type头:

  • JSON请求:Content-Type: application/json
  • XML请求:Content-Type: application/xml

附XML示例(请替换为你的实际结构):

<StudentRegistrationRequest>
    <StudentName>张三</StudentName>
    <Grade>10</Grade>
</StudentRegistrationRequest>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 03:52:39