json - Mensaje de publicación de API C#

CorePress2023-11-30  1

Intento publicar un mensaje y guardar los datos en posgres SQL. Obtengo mi información en JSON y luego llega a mi controlador C#:

[HttpPost()]
public IActionResult Update([FromBody]Person person)
{
    ObjectResult result = null;
    try
    {
        if (person.Save() == 1) result = new ObjectResult(new { success = true, message = "ok", person = person }) { StatusCode = (int)HttpStatusCode.OK };
        else result = new ObjectResult(new { success = false, message = "person not saved", person = person }) { StatusCode = (int)HttpStatusCode.NotModified };
    }
    catch (Exception ex)
    {

    }

    return result;
}

//Aquí sólo quiero comprobar en el futuro si el método se ejecuta //Desde aquí va a mi clase al método guardar:

    public int Save()
    {

        DBConnection.Connection.Open();


        string update = $"update {TABLE} set name = @name, email = @email, telefon = @telefon, where person_uid = @person_uid";

        NpgsqlCommand cmd;
            cmd = new NpgsqlCommand(update, DBConnection.Connection);

        cmd.Parameters.AddWithValue("@name", this.Name ?? (object)DBNull.Value);
        cmd.Parameters.AddWithValue("@email", this.Email ?? (object)DBNull.Value);
        cmd.Parameters.AddWithValue("@telefon", this.Telefon ?? (object)DBNull.Value);
        cmd.Parameters.AddWithValue("@person_uid", this.PersonUid ?? (object)DBNull.Value);
        cmd.Prepare();
        cmd.ExecuteNonQuery();

        DBConnection.Connection.Close();

        int result = 1;
        return result;
    }

Desde allí va hasta cmd.ExecuteNonQuery(). En mi navegador -> Red aparece el siguiente mensaje:



    System.InvalidOperationException: Cannot return null from an action method with a return type of 'Microsoft.AspNetCore.Mvc.IActionResult'.
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.EnsureActionResultNotNull(ObjectMethodExecutor executor, IActionResult actionResult)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,de;q=0.7
Connection: keep-alive
Content-Length: 95
Content-Type: application/json
Host: localhost
Referer: http://localhost/redpickle_export_21052020/person.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
Origin: http://localhost
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty

Sé que tengo una conexión DB porque escribí un método get para obtener todas las fechas en la misma tabla. También intenté guardar el número entero de cmd.ExecuteNonQuery(); pero esto tampoco funciona. Siempre recibo el mismo mensaje de error.

CONSOLA DE SALIDA:

The thread 0x3620 has exited with code 0 (0x0).
The thread 0x3c7c has exited with code 0 (0x0).
Exception thrown: 'Npgsql.PostgresException' in System.Private.CoreLib.dll
'w3wp.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App.1.1\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'w3wp.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App.1.1\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'w3wp.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App.1.1\System.Collections.Immutable.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request.

System.InvalidOperationException: Cannot return null from an action method with a return type of 'Microsoft.AspNetCore.Mvc.IActionResult'.
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.EnsureActionResultNotNull(ObjectMethodExecutor executor, IActionResult actionResult)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
'w3wp.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App.1.1\Microsoft.AspNetCore.Http.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

Este es mi método get para obtener todos los datos de la base de datos. Esto funciona bien

    public static List<Person> GetList()
        {
            List<Person> result = new List<Person>();
            try
            {

                DBConnection.Connection.Open();

                NpgsqlCommand command = new NpgsqlCommand();
                command.Connection = DBConnection.Connection;
                command.CommandText = $"select {COLUMNS} from {TABLE} order by name";
                NpgsqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    result.Add(new Person()
                    {
                        PersonId = reader.GetInt32(0),
                        PersonUid = (reader.IsDBNull(1) ? (int?)null : reader.GetInt32(1)),
                        Name = (reader.IsDBNull(2) ? string.Empty : reader.GetString(2)),
                        Password = (reader.IsDBNull(3) ? string.Empty : reader.GetString(3)),
                        Email = (reader.IsDBNull(4) ? string.Empty : reader.GetString(4)),
                        Telefon = (reader.IsDBNull(5) ? string.Empty : reader.GetString(5)),
                        LocationId = (reader.IsDBNull(6) ? (int?)null : reader.GetInt32(6)),


                    });
                }
                reader.Close();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                DBConnection.Connection.Close();
            }

            return result;
        }
  • ¿Puedes pegar el método de publicación completo, es decir, actualizar? - JyothiJ 6 de junio de 2020 a las 17:59
  • He completado la publicación. Bueno, creo un nuevo objeto con resultado para saber qué pasa -ddave 6 de junio de 2020 a las 18:02
  • ¿Por qué no depuras tu controlador y ves qué excepción se produce? - Crowcoder 6 de junio de 2020 a las 18:11
  • Además, ¿su tabla realmente se llama "TABLE"? ¿Y la sintaxis de {TABLE} es correcta en postgres? - Crowcoder6 de junio de 2020 a las 18:22
  • @Crowcoder sí, funciona. Ya tengo un método para obtener mis datos. Mi depuración ahora también está aquí -ddave 6 de junio de 2020 a las 18:24


------------------------

He encontrado el error. Mi declaración SQL tenía demasiado

string update = $"update {TABLE} set name = @name, email = @email, telefon = @telefon, where person_uid = @person_uid";
Respondido 6 de junio de 2020 a las 18:39 ddaveddave 1933 insignias de bronce
Su guía para un futuro mejor - libreflare
Su guía para un futuro mejor - libreflare