C# 发布 Web API

标签 c# post

我想在 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/

相关文章:

json - Restful API - 获取、放置、发布、删除需要多近?

ajax - 使用 polymer core-ajax 向 golang 服务器发布请求?

c# - 如何通过引用修改该字符串的非托管 C 库来发送字符串?

c# - Windows mobile消息框this.close()?

c# - C# 中的 WeakReference - 操作实例是如何丢失的?

http - 在真实设备上调用 api 时,Ionic 4 Http 失败响应(未知 url): 0 Unknown Error.

C++ 向 Web 服务器发送数据

c# - 从特定索引复制数组

c# - REST API 补丁请求

c# - ASP.NET MVC 发布不适用于弹出窗口