Call a Post Web API with multiple string parameters? - c#

How can we call the following web api ?
[HttpPost]
public bool ValidateAdmin(string username, string password)
{
return _userBusinessObject.ValidateAdmin(username, password);
}
I've written the following code, but it dosen't work 404 (Not Found)
string url = string.Format("api/User/ValidateAdmin?password={0}", password);
HttpResponseMessage response = Client.PostAsJsonAsync(url, username).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsAsync<bool>().Result;
Edit:
I'm dead sure about the Url, but it says 404 (Not Found)

i do like this for me in similar case :
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
HttpContent datas = new ObjectContent<dynamic>(new {
username= username,
password= password}, jsonFormatter);
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync("api/User/ValidateAdmin", datas).Result;
if (response != null)
{
try
{
response.EnsureSuccessStatusCode();
return response.Content.ReadAsAsync<bool>().Result;
...

Related

HttpClient post returns bad request in c#, works in postman

I'm trying to access a rest endpoint, https://api.planet.com/auth/v1/experimental/public/users/authenticate. It is expecting json in the request body.
I can get the request to work in Postman but not using c#. Using postman I get the expected invalid email or password message but with my code I get "Bad Request" no matter I try.
Here is the code that makes the request
private void Login()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.planet.com/");
client.DefaultRequestHeaders.Accept.Clear();
//ClientDefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
Data.User user = new Data.User
{
email = "myemail#company.com",
password = "sdosadf"
};
var requestMessage = JsonConvert.SerializeObject(user);
var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");
var response = client.PostAsync("auth/v1/experimental/public/users/authenticate", content).Result;
Console.WriteLine(response.ToString());
}
catch (WebException wex )
{
MessageBox.Show(wex.Message) ;
}
}
class User
{
public string email;
public string password;
}
Here are screen grabs form Postman that are working
The way to get this to work was to alter the content header "content-type". By default HTTPClient was creating content-type: application/json;characterset= UTF8. I dropped and recreated the content header without the characterset section and it worked.
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");
The issue is you are trying to call an async method without waiting for the response using await method or var task = method; task.Wait() Therefore, when you end up doing response.ToString() it returns the text you are seeing.
One way to handle this within a non-async method would be to do the following:
var task = client.PostAsync("auth/v1/experimental/public/users/authenticate", content);
task.Wait();
var responseTask = task.Content.ReadAsStringAsync();
responseTask.Wait();
Console.WriteLine(responseTask.Result);
Another way is to make the current method async by doing private async void Login() and then do:
var postResp = await client.PostAsync("auth/v1/experimental/public/users/authenticate", content);
var response = await postResp.Content.ReadAsStringAsync();
Console.WriteLine(response);
Create a Method Like this...
static async Task<string> PostURI(Uri u, HttpContent c)
{
var response = string.Empty;
var msg = "";
using (var client = new HttpClient())
{
HttpResponseMessage result = await client.PostAsync(u, c);
msg = await result.Content.ReadAsStringAsync();
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}
return response;
}
call In your Method
public void Login()
{
string postData ="{\"email\":\"your_email\",\"password\":\"your_password\"}";
Uri u = new Uri("yoururl");
var payload = postData;
HttpContent c = new StringContent(payload, Encoding.UTF8,"application/json");
var t = Task.Run(() => PostURI(u, c));
t.Wait();
Response.Write(t.Result);
}

Have a WebAPI Controller send an http request to another REST service

I'm creating WebAPI service, and I want it to redirect all incoming requests (GET,POST) to an external REST service and return the response (Json/html) to the original request to my WebAPI.
What is the best way to go about doing this? HttpResponseMessage or HttpWebResponse
[HttpGet]
[Route("api/Geocoder")]
public HttpWebResponse GetCandidates(string query)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://externalRestService.com/arcgis/rest/services/Geocode" + query);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response;
}
I also tried
[HttpGet]
public HttpResponseMessage Get()
{
try
{
HttpClient httpClient = new HttpClient()
{
BaseAddress = new Uri(""https://externalRestService.com/arcgis/rest/services/Geocode")
};
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = httpClient.GetAsync(requestUrl).Result;
return response;
}
catch
{
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.InternalServerError,
ReasonPhrase = "Internal Server Error"
};
}
}
Thanks in advance for any help. I'm newbie at .Net Core and webapis
The following approach worked for me.
public async Task<IHttpActionResult> GET(string query)
{
string _apiUrl = "http://foo.com/rest/services/Geocode?";
string _baseAddress = "http://foo.com/rest/services/Geocode?";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage = await client.GetAsync(_apiUrl + query);
if (responseMessage.IsSuccessStatusCode)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = responseMessage.Content;
return ResponseMessage(response);
}
}
return NotFound();
}

Can't authenticate correctly with headers (HttpClient)

I've checking many forums but I can't make it work. I'm trying to authenticate with headers to an url that will return a JSON string if authentication were successful. In Postman I simply used Get method with username and password in header to get the JSON data. What changes do I need to make my following C# code achieve same thing? I think I even failed to add username and password into headers.
public async Task<string> LogMeIn(string username, string password)
{
var client = new HttpClient {
BaseAddress = new Uri("http://x.com")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("grant_type","password"),
new KeyValuePair<string,string>("Username ", username),
new KeyValuePair<string,string>("Password", password)
});
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("/login", content); //should it be GetAsync?
var jsonResp = await response.Content.ReadAsStringAsync();
var jsonResult = JsonConvert.DeserializeObject<JsonResult>(jsonResp); //JsonResult = class for json
return jsonResult.token;
}
}

Make a post Request with azure new rest api (ressource manager)

I want to start my VM using the post Uri as described here https://msdn.microsoft.com/en-us/library/azure/mt163628.aspx
Since i don't have body in my request i get 403 frobidden. I can make a get Request without problem. Here is my code
public void StartVM()
{
string subscriptionid = ConfigurationManager.AppSettings["SubscriptionID"];
string resssourcegroup = ConfigurationManager.AppSettings["ressourgroupename"];
string vmname = ConfigurationManager.AppSettings["VMName"];
string apiversion = ConfigurationManager.AppSettings["apiversion"];
var reqstring = string.Format(ConfigurationManager.AppSettings["apirestcall"] + "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/start?api-version={3}", subscriptionid, resssourcegroup, vmname, apiversion);
string result = PostRequest(reqstring);
}
public string PostRequest(string url)
{
string content = null;
using (HttpClient client = new HttpClient())
{
StringContent stringcontent = new StringContent(string.Empty);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string token = GetAccessToken();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = client.PostAsync(url, stringcontent).Result;
if (response.IsSuccessStatusCode)
{
content = response.Content.ReadAsStringAsync().Result;
}
}
return content;
}
i've also tried this in the PostRequest
var values = new Dictionary<string, string>
{
{ "api-version", ConfigurationManager.AppSettings["apiversion"] }
};
var posteddata = new FormUrlEncodedContent(values);
HttpResponseMessage response = client.PostAsync(url, posteddata).Result;
with url=string.Format(ConfigurationManager.AppSettings["apirestcall"] + "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/start", subscriptionid, resssourcegroup, vmname);
I Get 400 Bad request
I found the solution. Needed to add role in Azure to allow starting/stopping the VM. That is why i received 4.3 forbidden.
Thank you

RestSharp requests on momentapp's restful api

So Im trying to set up RestSharp to use Moment Task scheduling according to the docs
http://momentapp.com/docs
here is my code.
public class MomentApi : ITaskScheduler
{
const string BaseUrl = "https://momentapp.com";
private RestResponse Execute(RestRequest request)
{
var client = new RestClient();
client.BaseUrl = BaseUrl;
request.AddParameter("apikey", "MYAPIKEYHERE", ParameterType.UrlSegment); // used on every request
var response = client.Execute(request);
return response;
}
public HttpStatusCode ScheduleTask(DateTime date, Uri url, string httpMethod, Uri callback = null)
{
var request = new RestRequest(Method.POST);
request.Resource = "jobs.json";
request.AddParameter("job[uri]", "http://develop.myapp.com/Something");
request.AddParameter("job[at]", "2012-06-31T18:36:21");
request.AddParameter("job[method]", "GET");
var response = Execute(request);
return response.StatusCode;
}
The problem is that it is always returnig HTTP 422
please help.
So this is what I ended up with.
found a sample here
http://johnsheehan.me/blog/building-nugetlatest-in-two-hours-3/
public HttpStatusCode ScheduleTask(DateTime date, Uri url, string httpMethod, Uri callback = null)
{
var request = new RestRequest("jobs.json?apikey={apikey}&job[uri]={uri}&job[at]={at}&job[method]={method}", Method.POST);
request.AddUrlSegment("uri", "http://develop.myapp.com/Something");
request.AddUrlSegment("at", "2012-03-31T18:36:21");
request.AddUrlSegment("method", "GET");
var response = Execute(request);
return response.StatusCode;
}
Im not completely sure on when I should use AddParameter and when I should use AddUrlSegment
but anyways it works now

Categories