【发布时间】:2021-06-02 22:29:45
【问题描述】:
这是我正在创建团队的 web api 方法的完整代码,我正在客户端中使用此方法。我已经通过 /api/Team/insertTeam 测试了这个发布方法,它在数据库中添加了新团队,但是在使用 httpclient/ 时出错了
[HttpPost]
[Route("insertTeam")]
public int insertTeam(Team team)
{
int teamid = -1;
try
{
using (SqlConnection con = new SqlConnection(ConString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("dbo.Team", con))
{
cmd.CommandText = "INSERT INTO team(Score, wideball, Noball, name, wickets, overs) VALUES(@score, @wideball, @noball, @name, @wickets, @overs); SELECT SCOPE_IDENTITY()";
cmd.Parameters.AddWithValue("@score", team.Score);
cmd.Parameters.AddWithValue("@wideball", team.Wideball);
cmd.Parameters.AddWithValue("@noball", team.Noball);
cmd.Parameters.AddWithValue("@name", team.Name);
cmd.Parameters.AddWithValue("@wickets", team.Wickets);
cmd.Parameters.AddWithValue("@overs", team.Overs);
teamid = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
}
catch (SqlException e)
{
System.Diagnostics.Debug.WriteLine("\n----------Error-----------\n");
System.Diagnostics.Debug.WriteLine(e.Message);
}
return teamid;
}
客户项目代码
private void AddTeam()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44382/api/Team");
//Adding teams
Team team1 = new Team
{
Name = tbteam1.Text,
Score = 0,
Wideball = 0,
Noball = 0,
Wickets = 0,
Overs = 0,
};
Team team2 = new Team
{
Name = tbteam2.Text,
Score = 0,
Wideball = 0,
Noball = 0,
Wickets = 0,
Overs = 0,
};
MediaTypeFormatter[] formatter = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };
HttpContent content = new ObjectContent<Team>(team1, formatter[0]);
HttpResponseMessage response = client.PostAsync(client.BaseAddress + "/insertTeam", content).Result;
}
客户端代码中的 postAsync 方法出错
System.AggregateException
HResult=0x80131500
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Client.team.AddTeam() in K:\LiveScoreSystemWebApi\Client\team.aspx.cs:line 259
at Client.team.GoBtn_Click(Object sender, EventArgs e) in K:\LiveScoreSystemWebApi\Client\team.aspx.cs:line 51
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
HttpRequestException: An error occurred while sending the request.
Inner Exception 2:
WebException: The underlying connection was closed: An unexpected error occurred on a receive.
Inner Exception 3:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Inner Exception 4:
SocketException: An existing connection was forcibly closed by the remote host
【问题讨论】:
-
错误很明显,即使代码不是,并且包含几个错误。 HTTP 连接突然关闭。至于代码 a) 看起来没有错误处理。您发布的内容类似于应用程序崩溃时写入 Windows 事件日志的事件。您需要添加适当的错误处理和日志记录。 b)您正在使用带有异步方法的
.Result。不要那样做。使用async/await。将方法的签名更改为async Task AddTeam()。 c) 代码在每次调用时创建一个新的 HttpClient 实例。 HttpClient 意味着可以重用,即使是来自多个线程 -
服务器是否在有机会响应甚至发送 500 错误之前就崩溃了?
-
在邮递员中工作但在客户端中无效
-
还有其他解决办法吗??
标签: c# asp.net-web-api