I an building an API that is essentially the middleware between a portal site and Salesforce. When trying to test and create a contact I am consistently getting a 400 bad request. I have tested that it is indeed logging in successfully to Salesforce.
Code I am using:
public async Task<SFDCContactsCreate> AddUser([FromBody] SFDCContactsCreate sfdcC)
{
var auth = new AuthenticationClient();
var url = Properties.Settings.Default.url1;
await auth.UsernamePasswordAsync(Properties.Settings.Default.consumerKey, Properties.Settings.Default.consumerSecret, Properties.Settings.Default.acctName, Properties.Settings.Default.acctPw + Properties.Settings.Default.token, url);
Console.Write(sfdcC);
var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
var cnt = new SFDCContactsCreate();
cnt.AccountId = sfdcC.AccountId;
cnt.FirstName = sfdcC.FirstName;
cnt.LastName = sfdcC.LastName;
cnt.Email = sfdcC.Email;
cnt.Title = sfdcC.Title;
cnt.Phone = sfdcC.Phone;
cnt.IsAdmin = sfdcC.IsAdmin;
var body = JsonConvert.SerializeObject(cnt);
var req = (HttpWebRequest)WebRequest.Create(Properties.Settings.Default.url2);
req.ContentType = "application/json";
req.Method = "post";
byte[] data = System.Text.Encoding.ASCII.GetBytes(body);
req.ContentLength = body.Length;
var os = req.GetRequestStream();
os.Write(data, 0, data.Length);
os.Close();
WebResponse resp;
try
{
resp = req.GetResponse();
}
catch (WebException ex)
{
resp = ex.Response;
}
if (resp == null) return null;
return sfdcC;
}
The Fiddler Test I am sending:
POST http://localhost:18178/UserCreate/ HTTP/1.1
Host: localhost:18178
Content-Length: 154
Content-Type: application/json
{
"AccountId" : "001c000000TT4VU",
"FirstName" : "John",
"LastName" : "Smith",
"Email" : "johnsmith@nowhere.com",
"Title" : "CEO",
"Phone" : "555-555-5555",
"IsAdmin" : false
}
I am not getting a specific line error and wonder if it is the test message I am sending. Any input would be quite helpful.
Best Answer
It looks like you are using the Force.com Toolkit for .NET. I can see you are creating an instance of the
ForceClient
to handle the authentication, but then appear to ignore it and use a raw HttpWebRequest to POST the JSON payload in.It's likely the
Properties.Settings.Default.url2
doesn't have the correct URL. Also, you aren't passing the AccessToken in the Authentication Bearer header.You need to use the ForceClient to perform the calls to Salesforce. It will have the active AccessToken (a.k.a. Session ID) and instance URL details that came back from the login operation.
Example code to insert a Contact Record from C# using the toolkit.