我想在 C# 中执行 HTTP Post 请求,但我不知道该怎么做。我在网上尝试了很多方法,但都抛出了不同的错误。
本质上我想对这个 api 做一个 post 请求:
http://localhost:57772/api/user/
我可以在 postman 中使用:
http://localhost:57772/api/user/?name=Paul
如有任何帮助,我们将不胜感激。这是我的代码
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "name", $"{activity.From.Name}" },
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://localhost:57772/api/user/", content);
错误是:
405 method not allowed
这是我的 Controller :
public IEnumerable<User> GetAllUsers()
{
return users;
}
public IHttpActionResult GetUsers(string name)
{
var user = users.FirstOrDefault((n) => n.name == name);
if (user == null)
{
return NotFound();
}
return Ok(user);
}
public IHttpActionResult PostNewUser(string name)
{
if (!ModelState.IsValid)
return BadRequest("Invalid data.");
var user = new User { name = name, message = "Hello3" };
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.broadcastMessage(name, "stop the chat");
return Ok(user);
}
}
最佳答案
using (WebClient client = new WebClient())
{
byte[] response = client.UploadData(“http://localhost:57772/api/user”, new NameValueCollection()
{
{“name”, “Paul”}
});
}
关于C# 发布 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441909/