System.Net.Http.HttpClient 4 Errors



我不能使用HttpClient对象从WPF应用程序中执行Post或Delete操作。但我可以做一个Get和GetById(字符串id)操作使用HttpClient。

HttpClient的命名空间是System.Net.Http。[我尝试使用Windows.Web.Http。HttpClient,但我无法在WPF项目中添加此dll作为参考。此httpclient dll必须从internet下载。)

下面是Delete操作的代码。下面的代码是在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 

下面是Get操作的工作代码,它的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种类型的错误。错误的详细信息如下所示:

系统。AggregateException: '发生一个或多个错误。'

错误1:HttpRequestException:发送请求时发生错误。

错误2:webeexception: The underlying connection was closed: a unexpected Error on a receive.

Error No.3: IOException: cannot to read data from the transport connection: An existing connection was forced close by the remote host.

错误4:SocketException:一个已存在的连接被远程主机强制关闭

我尝试了所有的方法来解决它。我还使用了async和await。当我使用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脚本注入。使用参数而不是字符串值。

我解决了这个问题,我的代码运行良好,没有任何错误。问题很简单。

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44390/");

我正在使用"http"而不是"https"在Uri。这就是问题所在

最新更新