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);
Related
I don't know how send values strings or models to a HttpPost-action
I want to send a value to a HttpPost-action in a API.
He reach the HttpPost-action. But the value of parameter name is NULL.
What do I wrong?
By example the value of "name" = "Netherlands".
public async Task<long> UpdateCountry(string name)
{
string url = $"{myApi}/Address/UpdateCountry";
var model = JsonConvert.SerializeObject(new KeyValuePair<string, string>("name", name));
long id = await Post(url, model);
return id;
}
than the process starts in the BaseClass... in the function Post.
protected async Task<dynamic> Post(string url, string data)
{
var client = new HttpClient();
var httpContent = new StringContent(data);
HttpResponseMessage responseMessage = await client.PostAsync(url, httpContent);
var result = await responseMessage.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<dynamic>(result);
}
And in the API the value of parameter name is NULL.
[HttpPost("UpdateCountry")]
public async Task<long> UpdateCountry(string name)
{
var countryId = _countryService.GetIdByName(name);
if (countryId == null)
{
var dto = new CountryDto() { Name = name };
....
countryId = await _countryService.Insert(dto);
}
else
{
dto.Name = name;
countryId = await _countryService.Update(dto);
}
return countryId.Value;
}
in the Client
public async Task<long> UpdateCountry(string name)
{
string url = $"{myApi}/Address/UpdateCountry";
var json = JsonConvert.SerializeObject(name);
long id = await Post(url, json, "text/json"); // or "application/json" when you use a model.
return id;
}
... and the BaseClass
protected async Task<dynamic> Post(string url, string data, string mediaType)
{
var client = new HttpClient();
var content = new StringContent(data, Encoding.UTF8, mediaType);
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<dynamic>(result);
}
return null;
}
... and in the API
[HttpPost("UpdateCountry")]
public async Task<long> UpdateCountry([FromBody] string name)
{
var countryId = _countryService.GetIdByName(name);
if (!countryId.HasValue)
{
var dto = new CountryDto() { Name = name };
....
countryId = await _countryService.Insert(dto);
}
else
{
....
dto.Name = name;
countryId = await _countryService.Update(dto);
}
return countryId.Value;
}
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; }
}
I have an Android app created with Xamarin in Visual Studio and I want to send a form data in json format to a Web Api created in C#. I tried a lot of methods from web an none worked.
Sometimes I get 500 Internal Server Error or sometimes I get null.
The last version I tried in WebApi is:
public HttpResponseMessage Post([FromBody]string value)
{
if (value == null || value == "") Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read subject/tutor from body");
var user = JsonConvert.DeserializeObject<UsersModel>(value);
dynamic json = System.Web.Helpers.Json.Decode(value);
string newName = json.Name;
string newSurname = json.Surname;
string newUsername = json.Username;
string newPassword = json.Password;
string insertNewUser = "INSERT INTO USERS(NAME,SURNAME,USERNAME,PASSWORD) VALUES (:name,:surname,:username,:password) ";
using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["Licenta"].ConnectionString))
{
OracleCommand cmd = new OracleCommand(insertNewUser, conn);
cmd.Parameters.Add("name", newName);
cmd.Parameters.Add("surname", newSurname);
cmd.Parameters.Add("username", newUsername);
cmd.Parameters.Add("password", newPassword);
cmd.ExecuteNonQuery();
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
The message I want to send to Web api is
{
"name": "Ionescu",
"surname": "Ralu",
"username": "ralucuta",
"password": "1235555",
"usertype":1
}
This is my Xamarin Android app code:
public async Task<UserAccount> SaveProduct(UserAccount product)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://blabla:80/test/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent content = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json");
// HTTP POST
HttpResponseMessage response = await client.PostAsync("api/Users/", content);
if (response.IsSuccessStatusCode)
{
string data = await response.Content.ReadAsStringAsync();
product = JsonConvert.DeserializeObject<UserAccount>(data);
}
}
return product;
}
public class UserAccount
{
public string name { get; set; }
public string surname { get; set; }
public string username { get; set; }
public string password { get; set; }
public int usertype { get; set; }
}
Your rest api won't be called since you are passing UserAccount object and you are expecting string. change your web api signature like this
[HttpPost]
[Route("api/Users/save")]
public HttpResponseMessage MyMethod(UserAccount userAccount)
{
//your api code
}
And in your android code
public async Task<UserAccount> SaveProduct(UserAccount product)
{
try {
using (var client = new HttpClient ()) {
client.BaseAddress = new Uri ("http://blabla:80/test/");
client.DefaultRequestHeaders.Accept.Clear ();
client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/json"));
var uri = new Uri ("http://blabla:80/test/api/Users/save");
string serializedObject = JsonConvert.SerializeObject (product);
HttpContent contentPost = new StringContent (serializedObject, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync (uri, contentPost);
if (response.IsSuccessStatusCode) {
var data = await response.Content.ReadAsStringAsync ();
UserAccount product = JsonConvert.DeserializeObject<UserAccount>(data);
return product;
}
}
}
catch (Exception) {
return null;
}
}
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"
}
]
}
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.
}
}