Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

c# - CreatedAtAction Returns 500 on Success

Overview
-Blazor Server project using REST API.
-HttpClient calls my API using PostJsonAsync<>
-Db is updated successfully and returns expected JSON
-API Controller Try/Catch does not throw exception, executes return CreatedAtAction()
-Output shows API returns 500: Internal Server Error
-When executing POST using Swagger, same line is executed and returns 201

I'm at a loss for what is going wrong. I've only been coding since July, so I'm hoping it's just my lack of experience that's blinding me to the obvious problem in my code. This is the offending method:

        public async Task<ActionResult<PlayerCharacter>> CreatePlayerCharacter(PlayerCharacter playerCharacter)
        {

            try
            {
                if (playerCharacter != null)
                {
                    var newPlayerCharacter = await _playerCharacterRepository.AddPlayerCharacter(playerCharacter);

                    //This is the last line of code to execute before the web app crashes with Status Code 500. Executes fine and returns 201 from Swagger.
                    return CreatedAtAction(nameof(GetPlayerCharacter), new { id = newPlayerCharacter.Id }, newPlayerCharacter);
                }

                return BadRequest();
            }
            catch (Exception e)
            {
                //This break point is not reached
                Console.WriteLine(e.StackTrace);
                return StatusCode(StatusCodes.Status500InternalServerError, "Error posting data to the database.");
            }
        }

GitHub Repo

question from:https://stackoverflow.com/questions/65873276/createdataction-returns-500-on-success

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The root cause of the problem is as yet not fully understood, but I do know how I fixed it.

After poke taught me how to look at the ASP.NET Core logs, I discovered this exception:
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.

Researching that lead me to several resources:

The solution may be that I should refactor my code to use DTOs (something I'll have to read up on because I don't understand that yet). In the meantime, the bandaid that will allow me to proceed is:

  1. Install NuGet Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
  2. In Statup.cs in ConfigureServices add
services.AddControllers().AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

Thank you to everyone who helped me think through this. I greatly appreciate your assistance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...