Reputation: 11
EDIT. The people who suggested fiddler were great. Turns out the API i was posting to freaked out because the c# application had no user-agent. So adding one to the header fixed it
I'm trying to use c# web client to to post to an api but seem to be running into a wall. I'm trying to use this code to post json to an api however all i get is 400 bad request and i'm not sure what is going on.
output = "{ \"id\": \"xxxxxx\", \"company\": \"test\", \"fname\": \"test\", \"lname\": \"test\", \"member_level\": \"Member\",\"status\": \"active\"}";
using (var client = new WebClient())
{
client.Headers.Add("token", "validtoken");
client.Headers.Add("Content-Type", "application/json");
client.UploadString(new Uri("url"), "POST", output);
}
I was able to use powershell to successfully post using a webrequest so i know the url and auth token are valid. but for whatever reason i can't get c# to post correctly. This is the working powershell command
curl url -Method POST -H @{"token" = "token"} -ContentType "application/json" -Body '{ "id": "xxxxxx", "company": "test", "fname": "test", "lname": "test", "member_level": "test","status": "active"}'
Upvotes: 1
Views: 5387
Reputation: 382
instead of
client.UploadString(new Uri("url"), "POST", output);
use
client.UploadData(url, "POST", Encoding.UTF8.GetBytes(output));
Upvotes: 3
Reputation: 3329
Just use built-in features of C# to keep code clean. When possible create classes that describe contracts for API communication. Use HttpClient when there is no need for low-level control. HttpClient can send these objects as JSON and you usually do not need to care about serialization issues.
This code should make a POST after you replaced url parts. Since you do not send the TOKEN this should raise a 401 error - you are not authorized. Add your valid token, delete the comment and this request should work.
using System;
using System.Collections.Generic;
using System.Net.Http;
public class User
{
public string Id { get; set; }
public string Company { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string MemberLevel { get; set; }
public string Status { get; set; }
}
class Program
{
static void CreateUser(User user)
{
using (var client = new HttpClient())
{
// posts to https://yourawesomewebsite.com/api/users
client.BaseAddress = new Uri("https://yourawesomewebsite.com");
//client.Headers.Add("token", "validtoken");
HttpResponseMessage response = client.PostAsJson("api/users", user);
response.EnsureSuccessStatusCode();
}
}
static void Main()
{
// Create a new user
User user = new User
{
Id = "xxxxx",
Company = "Test",
FName = "Test",
LName = "Test",
MemberLevel = "Test",
Status = "Active"
};
CreateUser(user);
}
}
Reference
Upvotes: 0