在Web API .Net Core中接受x-www-form-urlencoded

Rod*_*kan 9 asp.net-core-webapi asp.net-core-2.0

我有一个.Net Core Web API,当我尝试发布一些包含一些json的数据时,它返回415不支持的媒体错误.以下是Chrome调试器中返回内容的一部分:

Request URL:http://localhost:51608/api/trackAllInOne/set
Request Method:POST
Status Code:415 Unsupported Media Type
Accept:text/javascript, text/html, application/xml, text/xml, */*
Content-Type:application/x-www-form-urlencoded

action:finish
currentSco:CSharp-SSLA:__How_It_Works_SCO
data:{"status":"incomplete","score":""}
activityId:13
studentId:1
timestamp:1519864867900
Run Code Online (Sandbox Code Playgroud)

我认为这与我的控制器不接受application/x-www-form-urlencoded数据有关 - 但我不确定.我试过装饰我的控制器,Consumes但似乎没有用.

[HttpPost]
[Route("api/trackAllInOne/set")]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Post([FromBody] PlayerPackage playerPackage)
{ etc..}
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢.

以下代码在.Net 4.6.1中运行良好,我能够捕获并处理上面显示的帖子.

[ResponseType(typeof(PlayerPackage))]
public async Task<IHttpActionResult> PostLearningRecord(PlayerPackage playerPackage)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var id = Convert.ToInt32(playerPackage.ActivityId);
        var learningRecord = await _context.LearningRecords.FindAsync(id);
        if (learningRecord == null)
            return NotFound();
etc...
Run Code Online (Sandbox Code Playgroud)

Tao*_*hou 23

因为PlayerPackage,请求应该发送一个PlayerPackage Json对象,根据您的描述,您无法控制从其他地方发布的请求.

对于请求,其类型为 application/x-www-form-urlencoded,它将以字符串格式而不是Json对象发送{"status":"incomplete","score":""}的数据.如果你想接受{"status":"incomplete","score":""},我建议你改变下面的方法,然后将字符串转换为Object byNewtonsoft.Json

    [HttpPost]
    [Route("~/api/trackAllInOne/set")]
    [Consumes("application/x-www-form-urlencoded")]
    public IActionResult Post([FromForm] string data)
    {
        PlayerPackage playerPackage = JsonConvert.DeserializeObject<PlayerPackage>(data);
        return Json(data);
    }
Run Code Online (Sandbox Code Playgroud)


Aes*_*eir 20

尝试使用[FromForm]而不是[FromBody]

public IActionResult Post([FromForm] PlayerPackage playerPackage)
Run Code Online (Sandbox Code Playgroud)

FromBody - >如果你从JSON绑定

FromForm - >如果从Form参数绑定

注1:

您也可以完全删除[FromBody]并进行试用.因为你期望form-urlencoded应该告诉它绑定到对象.

  • 无论如何,我们可以让它同时适用于 application/x-www-urlencoded 和 application/json 吗?我正在创建两个具有相同路由名称的函数,并共享一个私有函数来完成这项工作,但我想知道是否有更简单的方法来支持 JSON 和 FORM 绑定。 (3认同)

Dan*_*elV 12

这对我有用:

[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Post([FromForm]IFormCollection value)
Run Code Online (Sandbox Code Playgroud)

  • `IFormCollection` 是关键。谢谢 (3认同)