如何在同一网址上使用[FromBody]和[FromForm]?

时间:2018-08-28 10:39:21

标签: c# asp.net-core .net-core asp.net-core-webapi asp.net-core-2.1

客户可以以JSONapplication/x-www-form-urlencoded格式向我发送数据。如何处理此请求,而不会分离到不同的URL?我尝试了两种情况。它行不通; 情况1:

[Route ( "api/[controller]" )]
[ApiController]
public class FirstController : ControllerBase
{
    [HttpPost]
    public string SomePostFromBody ( [FromBody] TestClass obj )
    {
        return obj.Prop1 + obj.Prop2;
    }

    [HttpPost]
    public string SomePostFromForm ( [FromForm] TestClass obj )
    {
        return obj.Prop1 + obj.Prop2;
    }
}

情况2:

[Route ( "api/[controller]" )]
[ApiController]
public class FirstController : ControllerBase
{
    [HttpPost]
    public string SomePost( [FromBody][FromForm] TestClass obj )
    {
        return obj.Prop1 + obj.Prop2;
    }
}

1 个答案:

答案 0 :(得分:0)

您为什么不手动读出这些值?

例如

[HttpPost]
public string SomePost()
{
    // Check if it's a Form value
    if(Request.Form != null) { // do something }
    else if(Request.Body != null) { // do something }
}

注意:上面的代码可能无法编译,我只是在这里快速编写了它。