c# - System.Net.Http.HttpClient 4 错误
问题描述
我无法使用 HttpClient 对象从 WPF 应用程序执行发布或删除操作。但我可以使用 HttpClient 执行 Get 和 GetById(string id) 操作。
HttpClient 的命名空间是 System.Net.Http。[我尝试使用 Windows.Web.Http.HttpClient,但我无法将此 dll 添加为 WPF 项目中的引用。此 httpclient dll 必须从 Internet 下载。]
这是删除操作的代码。下面的代码在 WPF 按钮的单击事件处理程序中。
public void DeleteByID(string id)
{
HttpClient client = new HttpClient(); //system.net.http
client.BaseAddress = new Uri("http://localhost:44390/");
var url = "api/Player/" + id;
HttpResponseMessage response = client.DeleteAsync(url).Result; **// ERROR here**
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
MessageBox.Show("User Deleted");
}
else
{
MessageBox.Show("Error Code");
}
}
其对应的 Web Api HttpDelete 方法如下所示:
public class PlayerController : ApiController
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = null;
[HttpDelete]
public bool DeleteByID(string id)
{
bool isdeleted = false;
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from tbl_Player where ID = '" + id + "'";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
isdeleted = true;
}
else
{
isdeleted = false;
}
con.Close();
return isdeleted;
}
catch
{
return isdeleted;
}
}
[HttpGet]
public DataTable Get()
{
DataTable dt = new DataTable();
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_Player";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
adp = new SqlDataAdapter(cmd);
dt.TableName = "tbl_Player";
adp.Fill(dt);
con.Close();
}
catch
{
}
return dt;
}
}
我的 Player 类如下所示:
public class Player
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Place { get; set; }
public string Country { get; set; }
public bool IsActive { get; set; }
}
在 SQLServer 中,表定义如下所示。
CREATE TABLE [dbo].[tbl_Player](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Age] [int] NULL,
[Place] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[IsActive] [bit] NULL,
CONSTRAINT [PK_tbl_Player] PRIMARY KEY CLUSTERED
下面是获取操作的工作代码,上面的控制器类中提到了它的 web api 方法。
public void GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44390/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/Player").Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var players = response.Content.ReadAsAsync<IEnumerable<Player>>().Result;
dgPlayers.ItemsSource = players; // dgPlayers is the datagrid in WPF Window.
}
else
{
MessageBox.Show("Error Code");
}
}
实际上我得到了 4 种类型的错误。错误的详细信息如下所述:
System.AggregateException:“发生了一个或多个错误。”
错误 1:HttpRequestException:发送请求时发生错误。
错误 2:WebException:底层连接已关闭:接收时发生意外错误。
错误 3:IOException:无法从传输连接读取数据:现有连接被远程主机强制关闭。
错误 4 : SocketException: 一个现有的连接被远程主机强行关闭
我尝试了所有方法来解决它。我也使用了异步和等待。当我使用 async 和 await 时,没有抛出错误,它卡在那里 - UI 变得没有响应。DeleteById 方法中抛出错误。调用没有到达 web api 删除 web 方法。
请帮我解决这个问题。
谢谢
解决方案
修复您的代码,删除连接关闭
SqlCommand cmd1 = new SqlCommand();
try
{
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = $"delete from tbl where ID = '{id}'";
cmd1.Connection = con;
if (con.State != ConnectionState.Open) con.Open();
int res = cmd1.ExecuteNonQuery();
con.Close();
}
catch
{
}
}
并记住 sql 脚本注入。使用参数而不是字符串值。
推荐阅读
- excel - Excel - 创建指向同名工作表的超链接
- python - 如何使用 iTune 的 API 下载文件并使用 python 导入字符串?
- javascript - DataTable JS 无法过滤小数列
- java - 集合 emptyList/singleton/singletonList/List/Set toArray
- swift - 改变 UIProgressView 的位置?
- java - 嵌套hashmap作为key获取值
- c++ - 每个子类组合的函数
- javascript - 错误:Windows 机器上的 LIBUSB_ERROR_ACCESS
- r - 将名称和时间数据从(每个时间内的名称)重塑为(每个名称的所有时间)
- java - 使用非静态方法作为泛型的枚举属性