相同方法.NET Core Web API上的多种类型[FromBody]

编程入门 行业动态 更新时间:2024-10-23 07:21:34
本文介绍了相同方法.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)])这样我就可以在 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 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]

本文发布于:2023-11-14 13:43:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587373.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多种   类型   方法   NET   Web

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!