相同方法.NET Core Web API上的多种类型[FromBody] [英] Multiple types [FromBody] on same method .net core web api

查看:578
本文介绍了相同方法.NET Core Web API上的多种类型[FromBody]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有POST方法的控制器,它将接收一个xml字符串,该字符串可以是2种类型。例如:

I have a controller with one POST method, which will receive an xml string which can be of 2 types. Eg:

[HttpPost("postObj")]
    public async Task<IActionResult> postObj([FromBody]firstClass data)
    {
        if (data != null)...

我希望能够绑定到同一条路由上的多种类型([HttpPost( postObj)])
这样我就可以在 http://127.0.0.1:5000/api/postObj 在主体中包含firstClass xml,在主体中包含secondClass xml,并采取相应的措施。

I would like to be able to bind to multiple types on the same route ([HttpPost("postObj")]) So that I can receive on http://127.0.0.1:5000/api/postObj with firstClass xml in the body, or secondClass xml in the body, and act accordingly.

我尝试制作另一种具有相同路线但类型不同的方法,例如:

I tried making another method with the same route but different type like:

    [HttpPost("postObj")]
    public async Task<IActionResult> postObj([FromBody]secondClass data)
    {
        if (data != null)...

但是我得到的是请求匹配多个动作导致歧义,正如预期的那样。

but I get "Request matched multiple actions resulting in ambiguity", as expected.

我尝试读取正文并进行检查然后序列化xml

I tried reading the body and doing a check then serializing the xml to the respective object, but that drastically reduced the performance.

我期望每秒最多100个请求,并且使用FromBody进行绑定可以使我得到,但是手动读取正文和序列化仅给我约15。

I am expecting up to 100 requests per second, and binding using FromBody is giving me that, but manually reading the body and serializing gives me only about 15.

如何实现?

推荐答案

您不能用相同的路线定义两个动作。动作选择器不考虑其参数类型。因此,为什么不合并此操作;

You can't define two actions with same route. Action Selector doesn't consider their parameter types. So, why don't you merge this actions;

public async Task<IActionResult> postObj([FromBody]EntireData data)
{
    if (data.FirstClass != null)
    {
        //Do something
    }
    if (data.SecondClass != null)
    {
        //Do something
    }
}

public class EntireData
{
    public FirstClass  firstClass { get; set; }

    public SecondClass secondClass { get; set; }
}

这篇关于相同方法.NET Core Web API上的多种类型[FromBody]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆