You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从动态对象中取值?Web API Controller提取OTP值求助

从动态键名的JSON中获取OTP值

方法一:通过ExpandoObject遍历键值对

将dynamic类型的请求参数转换为字典类型,直接提取动态键(即OTP值):

[HttpPost]
public IActionResult ReceiveOtp(dynamic request)
{
    var requestDict = (IDictionary<string, object>)request;
    if (requestDict.Count > 0)
    {
        string otpValue = requestDict.Keys.First();
        string status = requestDict[otpValue].ToString();
        // 后续处理OTP逻辑
        return Ok(new { Otp = otpValue, Status = status });
    }
    return BadRequest("未检测到OTP数据");
}

方法二:解析原始JSON字符串

如果动态绑定失效,直接读取请求体的原始JSON内容再解析:

[HttpPost]
public async Task<IActionResult> ReceiveOtp()
{
    using var streamReader = new StreamReader(Request.Body);
    string rawJson = await streamReader.ReadToEndAsync();
    
    var otpDict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(rawJson);
    if (otpDict?.Count > 0)
    {
        string otpValue = otpDict.Keys.First();
        return Ok(new { Otp = otpValue });
    }
    return BadRequest("无效的JSON格式");
}

方法三:用JObject处理动态结构(依赖Newtonsoft.Json)

借助JObject的属性遍历功能提取动态键:

using Newtonsoft.Json.Linq;

[HttpPost]
public IActionResult ReceiveOtp([FromBody] JObject request)
{
    var otpProperty = request.Properties().FirstOrDefault();
    if (otpProperty != null)
    {
        string otpValue = otpProperty.Name;
        string status = otpProperty.Value.ToString();
        return Ok(new { Otp = otpValue, Status = status });
    }
    return BadRequest("未找到有效OTP字段");
}

注意事项

  • 从调试窗口来看,你接收的JSON对象键名就是OTP值,值为状态描述,核心逻辑是提取这个动态键。
  • 确保请求的Content-Type设置为application/json,否则控制器无法正确绑定JSON数据。

内容的提问来源于stack exchange,提问作者touseefkhan4pk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:40:55