我尝试发布帖子,并将数据保存到posgres SQL。我用JSON获取信息,然后它出现在我的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;
}
//在这里,我只想在以后检查方法是否通过//从这里进入我的类的save方法:
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;
}
从那里一直到cmd.ExecuteNonQuery()。在我的浏览器->网络中,我收到以下消息:
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
我知道我有一个数据库连接,因为我编写了一个get方法来获取同一表中的所有日期。我也尝试保存cmd.ExecuteNonQuery()的整数;但这也不起作用。我总是收到相同的错误消息。
OUTPUT CONSOLOE:
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\3.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\3.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\3.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\3.1.1\Microsoft.AspNetCore.Http.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
这是我的get方法,用于获取数据库中的所有数据。效果很好
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;
}
我发现了错误。我的SQL语句的,
过多
string update = $"update {TABLE} set name = @name, email = @email, telefon = @telefon, where person_uid = @person_uid";