C# HTTP 500:导致错误的SQL连接字符串
我正在使用ASP.NET开发一个API。在某一点上,我需要一个方法来调用另一个方法。这两种方法都使用存储过程:C# HTTP 500:导致错误的SQL连接字符串,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我正在使用ASP.NET开发一个API。在某一点上,我需要一个方法来调用另一个方法。这两种方法都使用存储过程: public async Task<IHttpActionResult> GetTeamById(string TeamId) { DataTable Result = new DataTable(); SqlCommand Command = new SqlCommand("GetTeam", ConnectionStrin
public async Task<IHttpActionResult> GetTeamById(string TeamId)
{
DataTable Result = new DataTable();
SqlCommand Command = new SqlCommand("GetTeam", ConnectionString);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("@TeamId", TeamId);
using (ConnectionString) /defined above
{
try
{
ConnectionString.Open();
using (SqlDataReader DataReader = Command.ExecuteReader())
{
Result.Load(DataReader);
return Ok(Result);
}
}
catch
{
return InternalServerError();
}
}
}
public async Task<IHttpActionResult> UpdateTeam(string TeamId)
{
SqlCommand Command = new SqlCommand("UpdateTeam", ConnectionString);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("@Id", TeamId);
using (ConnectionString)
{
try
{
ConnectionString.Open();
int returnvalue = (int) Command.ExecuteScalar();
if (returnvalue == 1)
return BadRequest();
else
await GetTeamById(TeamId);
}
catch
{
return InternalServerError();
}
}
}
public异步任务GetTeamById(字符串TeamId)
{
DataTable结果=新DataTable();
SqlCommand=newsqlcommand(“GetTeam”,ConnectionString);
Command.CommandType=CommandType.storedProcess;
Command.Parameters.AddWithValue(“@TeamId”,TeamId);
使用(ConnectionString)/上述定义
{
尝试
{
ConnectionString.Open();
使用(SqlDataReader=Command.ExecuteReader())
{
结果.加载(数据读取器);
返回Ok(结果);
}
}
抓住
{
返回InternalServerError();
}
}
}
公共异步任务UpdateTeam(字符串TeamId)
{
SqlCommand=newsqlcommand(“updatetem”,ConnectionString);
Command.CommandType=CommandType.storedProcess;
Command.Parameters.AddWithValue(“@Id”,TeamId);
使用(连接字符串)
{
尝试
{
ConnectionString.Open();
int returnvalue=(int)Command.ExecuteScalar();
如果(返回值==1)
返回请求();
其他的
等待GetTeamById(TeamId);
}
抓住
{
返回InternalServerError();
}
}
}
我面临的问题是,当调用updateeam
方法时,该代码抛出500个内部服务器错误。我发现问题出现在GetTeamById
函数中的ConnectionString.Open()
行
我想那可能是因为连接还在打开?但这不正是人们使用using()
的原因吗?我如何解决这个问题
谢谢你的支持 当我连接到一个程序时,我总是遵循这个标准:
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
当我连接到程序时,我始终遵循此标准:
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
为什么不像使用(var dbAbel_Reporting=new Abel_reportingportalities())那样使用您的连接字符串呢{也就是说,将它用于var并创建它的新实例。.为什么不像使用(var dbAbel_Reporting=new Abel_reportingportalities())那样使用您的连接字符串呢{也就是说,使用它到var中并创建它的新实例..好的,谢谢!应用了它,它就像预期的那样工作:)好的,谢谢!应用了它,它就像预期的那样工作:)