繁体   English   中英

C#Post Web API

[英]C# Post Web API

我想用C#发出HTTP Post请求,但我只是不知道该怎么做。 我在网上尝试了很多方法,但是却抛出了不同的错误。

本质上,我想对此API进行发布请求:

http://localhost:57772/api/user/

我可以在邮递员中执行以下操作:

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方法不允许

这是我的控制器:

    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”}
     });
}

我终于找到了这一解决方案:

string url = "http://stopbyte.com"; // Just a sample url
WebClient wc = new WebClient();

wc.QueryString.Add("parameter1", "Hello world");
wc.QueryString.Add("parameter2", "www.stopbyte.com");
wc.QueryString.Add("parameter3", "parameter 3 value.");

var data = wc.UploadValues(url, "POST", wc.QueryString);

// data here is optional, in case we recieve any string data back from the POST request.
var responseString = UnicodeEncoding.UTF8.GetString(data);

如何在C#中使用WebClient POST请求发送参数数据

感谢那些质疑我使用POST还是GET的人的帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM