簡體   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