简体   繁体   中英

C# Post Web API

I want to do a HTTP Post request in C# but I just don't know how to do that. I have tried a lot of methods online but it threw different errors.

Essentially I want to do a post request to this api:

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

I can do this in postman with:

http://localhost:57772/api/user/?name=Paul

Any help would be appreciated. Here is my code

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

And the error is:

405 method not allowed

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

I finally found the solution for this one:

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

from How to send Parameters Data using WebClient POST request in C#

And thanks to the people who questions whether I am using POST or GET being so helpful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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