【发布时间】:2020-10-05 12:17:04
【问题描述】:
我已经创建了一个简单的 Asp.Net Api 来在 Winforms 应用程序中显示学生的信息,但是,现在我想要创建一个从 Windows Forms 应用程序接受值并将这些值插入数据库的 Api。我怎么能创造这样的东西?这是我到目前为止所尝试的:
Asp.Net API:
[Route("api/[controller]")]
[ApiController]
public class Students : ControllerBase
{
SqlConnection con;
SqlCommand cmd;
[HttpPost]
public void Post()
{
string name = "janet";
string age = "12";
con = new SqlConnection("ConnectionString");
cmd = new SqlCommand("insert into People(name,age) values(@name,@age)", con);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@age", age);
con.Open();
cmd.ExecuteNonQuery();
}
}
Windows 窗体应用程序:
private void button1_Click(object sender, EventArgs e)
{
action();
}
HttpResponseMessage response;
HttpClient client;
async void action()
{
client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44338/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await client.GetAsync("api/Students");
if (response.IsSuccessStatusCode)
{
MessageBox.Show("item added successfully");
}
}
我想将 Api 中的 name 和 age 变量更改为我在 Winforms 中输入的任何值。
PS:我知道我在 winforms 中使用了client.GetAsync,它应该是client.PostAsync,但我不知道应该传递什么参数。
感谢您的帮助。
【问题讨论】:
-
您应该阅读You're using HttpClient wrong and it's destabilizing your software,因为您正在破坏那里的关键指南之一。您可能对Flurl 有更好的体验,它的语法更简洁,并为您处理了一些棘手的问题。
-
您应该避免使用
async void,除了事件处理程序本身。您的操作方法应该返回一个任务,然后 button1_Click 应该等待它,因此 button1_Click 必须标记为异步。
标签: c# asp.net winforms api asp.net-core