首页 > 解决方案 > 当内容类型为application / x-www-form-urlencoded .net core时如何使用帖子数据

问题描述

我有一个用例,我需要接受application/x-www-form-urlencoded发布数据并使用查询字符串

[httpPost]
public void GetDetails([FromQuery] username)
{
   using (var reader = new StreamReader(Request.Body))
   {
       try
       {
           var line = await reader.ReadToEndAsync();
       }
       catch(exception ex)
       {
         //Do something
       } 
   }
}

为此,当我尝试上面的Request.Body流时null

我有一个解决方案来删除[FromQuery]和读取查询字符串,Reqeust.QueryString但我们还有其他选择吗

标签: c#razorasp.net-coreasp.net-core-2.0model-binding

解决方案


[FromQuery]并且[FromForm]可以相互结合使用来绑定参数。

[HttpPost]
public IActionResult GetDetails([FromQuery] string username, [FromForm] string formData) {
    //...Do something
    return Ok();
}

虽然上面的示例采用字符串中的表单数据,但如果需要,它也可用于绑定到更复杂的对象。

ASP.NET Core 中的参考模型绑定


推荐阅读