I managed to get access token with my code,
private async Task<string> GetAccessToken()
{
string refreshToken = string.Empty;
string accessToken = string.Empty;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://demo.docusign.net/restapi/v2/oauth2/token");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string body =
"username=user%40company.net&password=mypassword&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxc&grant_type=password&scope=api";
HttpContent content = new System.Net.Http.StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage messge = await client.PostAsync("https://demo.docusign.net/restapi/v2/oauth2/token", content);
//string description = string.Empty;
if (messge.IsSuccessStatusCode)
{
string result = messge.Content.ReadAsStringAsync().Result;
dynamic returnObj = JsonConvert.DeserializeObject(result);
var scope = returnObj.scope.Value;
accessToken = returnObj.access_token.Value;
}
return accessToken;
}
This gives me the access token,
Now I am trying to use that token and add a user to the account,
private async Task<string> AddUser(string accessToken, string usersBaseUri)
{
usersBaseUri = "https://demo.docusign.net/restapi/v2/accounts/<myaccountId>/users";
string resultStr = string.Empty;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(usersBaseUri);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
DocuSignUser user = new DocuSignUser();
user.Email = "user2#company.net";
user.UserName = "user2#company.net";
user.FirstName = "user2";
user.LastName = "dev";
var json = JsonConvert.SerializeObject(user);
HttpContent content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage messge = await client.PostAsync(usersBaseUri, content);
//string description = string.Empty;
if (messge.IsSuccessStatusCode)
{
string result = messge.Content.ReadAsStringAsync().Result;
dynamic returnObj = JsonConvert.DeserializeObject(result);
var scope = returnObj.scope.Value;
accessToken = returnObj.access_token.Value;
}
return resultStr;
}
Here is the Docusign User class I use to serialize,
public class DocuSignUser
{
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("userName")]
public string UserName { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
}
User api is not supported in the .Net SDK. Therefor I had to write this code by referring to Docusign Api test playground and checking the Request/Response with Fiddler.
Appreciate any help on this.
EDIT
Here is the POST request
POST https://demo.docusign.net/restapi/v2/accounts/156xxxx/users HTTP/1.1
Accept: application/json
Authorization: Bearer *******<AccessToken>
Content-Type: application/json; charset=utf-8
Host: demo.docusign.net
Content-Length: 100
Expect: 100-continue
{"email":"user1#company.net","userName":"user1#company.net","firstName":"Sam1","lastName":"Cooper1"}
Found the answer,
Issue was with the Json message.
Required Json format is in the following format as per Api Guide
{
"newUsers":[
{
"email":"user#company.net",
"firstName":"name1",
"lastName":"lastname1",
"password":"Password01",
"userName":"user1#bcompany.net"
}
]
}
Related
I've been trying to use HttpClient, to connect to an API. I'm able to send a GET request and recieve the desired data that I want from it through Postman and Fiddler, without issue.
The issue is that the json file i get from the HttpClient is: []
The HttpClient gives me the Status 200 while providing me with an empty array.
public class CoolModel
{
public string name { get; set; }
public int itemId{ get; set; }
public string Devicename{ get; set; }
}
var username = _config["Username"];
var password = _config[":Password"];
var encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", username, password)));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);
httpClient.DefaultRequestHeaders.Add("ApiKey", _config["ApiKey"]);
httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
httpClient.DefaultRequestHeaders.Add("User-Agent", "C# App");
HttpResponseMessage httpResponse = httpClient.GetAsync(_config["Url"] + $"item?ID={_config["ItemId"]}&DeviceName={_config["DeviceName"]}").Result;
var json = await httpResponse.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeObject<List<CoolModel>>(json);
This will return the following:
[]
While what I want is:
[
{
"name":"John",
"itemId":30,
"Devicename":"something"
}
]
My json that is returned is also
[]
Below is a demo about using HttpClient to connect to an API, you can refer to it.
[Route("home")]
public class HomeController : Controller
{
[HttpGet]
public async Task<IActionResult> IndexAsync()
{
string url = $"https://localhost:7272/weatherForecast";
HttpClientHandler httpClientHandler = new HttpClientHandler();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
HttpClient httpClient = new HttpClient(httpClientHandler)
{
BaseAddress = new Uri(url)
};
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
httpClientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
HttpResponseMessage response = await httpClient.GetAsync(string.Empty, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeObject<List<WeatherForecast>>(json);
return View(content);
}
Result:
My issue was that the Url
var url = _config["Url"] + $"item?ID={_config["ItemId"]}&DeviceName={_config["DeviceName"]}"
Contained empty new lines, so I had to remove the new lines.
so I added the following to my url
.Replace("\n", "").Replace("\r", ""));
HttpResponseMessage httpResponse = await httpClient.GetAsync(url.Replace("\n", "").Replace("\r", ""));```
Fix your model, id should be an integer
public class CoolModel
{
public string name { get; set; }
public int id { get; set; }
public string devicename { get; set; }
}
when I post username and password and IP address I got only an empty response.
my C# code is:
public async void APILogin(string user, string pass, string ip)
{
var person = new Userinfo { username = user, password = pass, ip = ip };
var json = JsonConvert.SerializeObject(person);
var data = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
var url = new Uri("http://localhost/login/dblogin.php") ;
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(url,content:data);
HttpContent content = response.Content;
string myContent = await content.ReadAsStringAsync();
MessageBox.Show(myContent, "Info");
}
public class Userinfo
{
public String username { get; set; }
public String password { get; set; }
public String ip { get; set; }
}
I used this and it is worked.
var url = "http://localhost/login/dblogin.php";
HttpClient client = new HttpClient();
StringContent data = new StringContent("username="+user+"&password="+pass+"&ip="+ip);
data.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await client.PostAsync(url, data);
response.EnsureSuccessStatusCode();
HttpContent content = response.Content;
string myContent = await content.ReadAsStringAsync();
loginResp apiResponse = JsonConvert.DeserializeObject<loginResp>(myContent);
I have a method that is meant to post a request. Basically, this method takes an uri, a userRequest to send as Json payload and a bearer token.
public async Task<UserResponse> CreateUser(Uri url, UserRequest userRequest, string token)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var req = new HttpRequestMessage(HttpMethod.Post, url);
req.Content = new StringContent(
userRequest.ToString(),
Encoding.UTF8,
"application/json"
);
var response = await client.SendAsync(req);
string output = await response.Content.ReadAsStringAsync();
UserResponse returnValue = JsonConvert.DeserializeObject<UserResponse>(output);
return returnValue;
}
My issue is that the response is an error 422.
My request model is the following :
public class UserRequest
{
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "isadmin")]
public bool IsAdmin{ get; set; }
[JsonProperty(PropertyName = "password")]
public string Password { get; set; }
public UserRequest(string email, bool sysadmin, string password)
{
Email = email;
IsAdmin = isAdmin;
Password = password;
}
}
In fact I do think my issue is that I don't pass correctly the object in the post request or that the keys are taken from the model and not from property name.
I mean that I send
{ "Email": "myMail#mail.com", "Password": "passwd", "IsAdmin": true }
Instead of :
{ "email": "myMail#mail.com", "password": "passwd", "isadmin": true }
My question is to know if there's a way to use JsonProperty names instead of Properties names
req.Content = new StringContent(
userRequest.ToString(),
Encoding.UTF8,
"application/json"
);
Have you tried using Newtonsoft.JSON to Serialize the object?
JsonConvert.Serialize(userRequest) should do the trick
I have this code:
private const string route = "/api/Print";
public bool Update(string header, string tc)
{
bool success = false;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("my uri");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var print = new Print { CompanyRef = new Guid(), Header = header, TC = tc };
var response = client.PutAsJsonAsync(route, print);
}
success = true;
return success;
}
public sealed class Print
{
public string Header { get; set; }
public string TC { get; set; }
public System.Guid CompanyRef { get; set; }
}
I call it like so:
Update(" header", " string tc");
In C# desktop app it works.
In Windows 10 IoT on a Raspberry Pi2 device it does not work.
Yet, when i am calling a Get from my Web API server *in Iot) it works fine.
?
I am using this code for a year now and it works:
using Windows.Web.Http;
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
try
{
var o = new
{
operation = "NewEvent",
location_id = locationID,
eventName = eventName
};
HttpStringContent content = new HttpStringContent(JsonConvert.SerializeObject(o), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(new Uri(urlPostData), content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// TODO: Do something with the responseBody
}
catch (Exception)
{
// TODO: Deal with exception - could be a server not found, 401, 404, etc.
}
}
I'm trying to retrieve an access token from Google's authorization endpoint, however I keep getting 401: Unauthorized.
I'm pretty sure all the values being sent (authorization code, client's id, client's secret, redirect uri and grant type) are correct.
My code is the following:
using (HttpClient client = new HttpClient()) {
IEnumerable<KeyValuePair<string,string>> data = new List<KeyValuePair<string,string>>
{
new KeyValuePair<string,string>("code", "CODE_HERE"),
new KeyValuePair<string,string>("client_id", "CLIENT_ID_HERE"),
new KeyValuePair<string,string>("client_secret", "CLIENT_SECRET_HERE"),
new KeyValuePair<string,string>("redirect_uri", "REDIRECT_URI_HERE"),
new KeyValuePair<string,string>("grant_type", "authorization_code"),
}
HttpContent content = new FormUrlEncodedContent(data);
/* I'm getting 401 Unauthorized */
HttpResponseMessage response = await client.PostAsync("https://www.googleapis.com/oauth2/v3/token", content);
}
The response's JSON is:
{
"error": "invalid_client",
"error_description": "Unauthorized"
}
However, I'm copying & pasting the client's id and client's secret from my Google Developer control panel, so there is no way they are wrong.
Any help?
Here is what worked for me. In this sample, I'm using the RefreshToken to get an AccessToken.
var client_id = ConfigurationManager.AppSettings.Get("GoogleClientId");
var client_secret = ConfigurationManager.AppSettings.Get("GoogleSecret");
var grant_type = "refresh_token";
var url = "https://www.googleapis.com/oauth2/v4/token";
IEnumerable<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("client_id", client_id),
new KeyValuePair<string,string>("client_secret", client_secret),
new KeyValuePair<string,string>("grant_type", grant_type),
new KeyValuePair<string,string>("refresh_token", refreshToken),
};
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpContent contentPost = new FormUrlEncodedContent(data);
HttpResponseMessage response = await client.PostAsync(url, contentPost);
var result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<GoogleAPIAuth>(result);
Here is my GoogleAPIAuth class.
public class GoogleAPIAuth
{
public string client_secret { get; set; }
public string grant_type { get; set; }
public string refresh_token { get; set; }
public string client_id { get; set; }
public string access_token { get; set; }
public string expires_in { get; set; }
public string token_type { get; set; }
}