繁体   English   中英

"ASP.NET Core 3.1:Web Api:相同的发布方法:多种类型的 Json 对象"

[英]ASP.NET Core 3.1: Web Api: Same Post Method: Multiple types of Json Objects

我有一个要求,我的 POST 方法(单个端点)需要接受不同类型的 json 字符串并对其进行操作。 我尝试了以下方法并收到 404 错误:

using Newtonsoft.Json.Linq;

public async Task<IActionResult> Post([FromBody] string jsonString)
    {
        if (string.IsNullOrEmpty(jsonString)) return BadRequest();
        try
        {
            JObject _jsonObject = JObject.Parse(jsonString);
            string _response = string.Empty;

            if(_jsonObject != null)
            {
                string messageType = _jsonObject.GetValue("objectType").ToString();
                if(messageType.ToLower() == "type1")
                {                        
                    _response = await dataRepository.InsertType1Record(_jsonObject );                        
                } else if (messageType.ToLower() == "type2")
                {
                    _response = await dataRepository.InsertType2Record(_jsonObject );                        
                } else if (messageType.ToLower() == "type3")
                {
                    _response = await dataRepository.InsertType3Record(_jsonObject );
                }
                return Ok(_response);
            }
            return BadRequest();
        }
        catch (Exception e)
        {
            _logger.LogTrace(e, "Exception Error");
            return BadRequest();
        }

    }

尝试将内容类型更改为

application/json; charset=utf-8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM