【问题标题】:How to bind a POST request with no Content-Type Web API .Net core 2.1?如何绑定没有 Content-Type Web API .Net core 2.1 的 POST 请求?
【发布时间】:2019-01-15 20:29:01
【问题描述】:

我试图捕获服务器发送给我的 HTTP 请求中包含的 XML,但 HTTP 不包含 Content-Type。 我无权访问服务器,因此无法添加 Content-Type。

如果我尝试将请求正文与 [FromBody] 绑定,则会收到 415 Unsupported Media Type 的错误

[HttpPost("voicebiometricsengine")]
    public async Task<IActionResult> VoiceBiometricsEngine([FromBody] XmlDocument analytics)
    {        
        return Ok();
    }

如果我尝试将正文作为字符串获取,则字符串为 Null

 [HttpPost("voicebiometricsengine")]
    public async Task<IActionResult> VoiceBiometricsEngine(string analytics)
    {

        return Ok();
    }

您可以在下图中看到 HTTP 包:

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    如果没有内容类型,框架在尝试与您的方法参数绑定时不知道如何解析正文。

    一种选择是在方法内部手动读取请求正文

    [HttpPost("voicebiometricsengine")]
    public async Task<IActionResult> VoiceBiometricsEngine(string analytics)
    {
        using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
        {  
            var body = await reader.ReadToEndAsync();
        }
        return Ok();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 2018-08-27
      • 2021-03-26
      相关资源
      最近更新 更多