[英]Bind route and body values to same model on post request
Is it possible to bind values from both the URL route and the body to the same model during a post request?是否可以在发布请求期间将 URL 路由和主体的值绑定到同一个 model?
For example:例如:
[Route("test")]
public class TestController : ControllerBase
{
[HttpPost("{valueFromRoute}/post")]
public IActionResult Post(Model model)
{
return new JsonResult(model);
}
}
public class Model
{
[FromRoute]
public string ValueFromRoute { get; set; }
[FromBody]
public string ValueFromBody { get; set; }
}
I'd like to call this endpoint as follows:我想按如下方式调用此端点:
However using this code, only the ValueFromRoute
is populated:但是,使用此代码时,只会填充
ValueFromRoute
:
{
"valueFromRoute": "some-route-value",
"valueFromBody": null
}
I'm guessing the answer is probably "no", and that two separate models would have to be used, such as:我猜答案可能是“否”,并且必须使用两个单独的模型,例如:
[Route("test")]
public class TestController : ControllerBase
{
[HttpPost("{valueFromRoute}/post")]
public IActionResult Post([FromRoute] RouteModel routeModel, [FromBody] BodyModel bodyModel)
{
return new JsonResult(new
{
ValueFromRoute = routeModel.ValueFromRoute,
ValueFromBody = bodyModel.ValueFromBody
});
}
}
public class RouteModel
{
public string ValueFromRoute { get; set; }
}
public class BodyModel
{
public string ValueFromBody { get; set; }
}
Calling this in the exact same way as in the screenshot above works as expected, populating both values on their respective objects, and outputting the following:以与上面屏幕截图完全相同的方式调用它,按预期工作,将两个值填充到各自的对象上,并输出以下内容:
{
"valueFromRoute": "some-route-value",
"valueFromBody": "Some value from body"
}
So I have a potential solution, but it's not my preferred solution.所以我有一个潜在的解决方案,但它不是我的首选解决方案。 Ideally, I'd like to bind both route & body values to the same model, if possible.
理想情况下,如果可能的话,我想将路由和正文值绑定到相同的 model。
I found this related question on GitHub, which helped me understand that the body must be deserialised to a class object, even if it only contains one property, like my example above.我在 GitHub 上发现了这个相关问题,它帮助我理解必须将正文反序列化为 class object,即使它只包含一个属性,如我上面的示例。
The solution to my example above is simply to create a new class for the body to be deserialised to, and add this to my main model expected by my action method.我上面示例的解决方案只是为要反序列化的主体创建一个新的 class,并将其添加到我的操作方法预期的主要 model 中。
[Route("test")]
public class TestController : ControllerBase
{
[HttpPost("{valueFromRoute}/post")]
public IActionResult Post(Model model)
{
return new JsonResult(model);
}
}
public class Model
{
[FromRoute]
public string ValueFromRoute { get; set; }
// Map body to simple class object rather than a primitive type
[FromBody]
public BodyModel BodyModel { get; set; }
}
public class BodyModel
{
public string ValueFromBody { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.