I'm working on making a POST request using my Xamarin form to send data to an Action in my controller in my WebAPI project. The code with breakpoints doesn't go beyond
client.BaseAddress = new Uri("192.168.79.119:10000");
I have namespace System.Net.Http and using System mentioned in the code.
private void BtnSubmitClicked(object sender, EventArgs eventArgs)
{
System.Threading.Tasks.Task<HttpResponseMessage> statCode = ResetPassword();
App.Log(string.Format("Status Code", statCode));
}
public async Task<HttpResponseMessage> ResetPassword()
{
ForgotPassword model = new ForgotPassword();
model.Email = Email.Text;
var client = new HttpClient();
client.BaseAddress = new Uri("192.168.79.119:10000");
var content = new StringContent(
JsonConvert.SerializeObject(new { Email = Email.Text }));
HttpResponseMessage response = await client.PostAsync("/api/api/Account/PasswordReset", content); //the Address is correct
return response;
}
Need a way to make a Post request to that Action and sending that String or the Model.Email as a parameter.
You need to use a proper Uri and also await the Task being returned from the called method.
private async void BtnSubmitClicked(object sender, EventArgs eventArgs) {
HttpResponseMessage response = await ResetPasswordAsync();
App.Log(string.Format("Status Code: {0}", response.StatusCode));
}
public Task<HttpResponseMessage> ResetPasswordAsync() {
var model = new ForgotPassword() {
Email = Email.Text
};
var client = new HttpClient();
client.BaseAddress = new Uri("http://192.168.79.119:10000");
var json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var path = "api/api/Account/PasswordReset";
return client.PostAsync(path, content); //the Address is correct
}
Related
I am getting error cannot send a content-body with this verb-type. I am calling a GET Endpoint from a C# VSTO desktop application. What am I doing wrong.
public static string GetCentralPath(LicenseMachineValidateRequestDTO licenseMachine)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Properties.Settings.Default.Properties["JWT"].DefaultValue.ToString());
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{Constants.URL.APIBase}licensemachine/GetCentralPath"),
Content = new StringContent(JsonConvert.SerializeObject(licenseMachine), Encoding.UTF8, "application/json"),
};
using (HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult()) // Causing ERROR
{
var result = GetStringResultFromHttpResponseMessage(response, true);
if (string.IsNullOrEmpty(result))
return null;
return JsonConvert.DeserializeObject<string>(result);
}
}
}
The end point looks like the following:
[HttpGet("GetCentralPath")]
public async Task<IActionResult> GetCentralPath(LicenseMachineValidateRequestDTO dto)
{
// Some code
}
fix the action, you cannot send body data with get, see this post
HTTP GET with request body
[HttpPost("GetCentralPath")]
public async Task<IActionResult> GetCentralPath(LicenseMachineValidateRequestDTO dto)
and fix request , replace Method = HttpMethod.Get with Post, this is what generates an error
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{Constants.URL.APIBase}licensemachine/GetCentralPath"),
Content = new StringContent(JsonConvert.SerializeObject(licenseMachine), Encoding.UTF8, "application/json"),
};
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);
}
I've been trying to post a message along with a link, I can send one POST request, but I am not sure how would one send two.
Here's my code:
private void Button2_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://graph.facebook.com");
string message = "hello";
string link = "www.facebook.com"
var payload = GetPayload(new {message});
HttpResponseMessage response2 = client.PostAsync($"me/feed?access_token={TextBox1.Text}", payload).Result;
}
}
private static StringContent GetPayload(object data)
{
var json = JsonConvert.SerializeObject(data);
return new StringContent(json, Encoding.UTF8, "application/json");
}
I am not sure how can I include the link too along with the message.
Al-right it turns out that the variable link should be passed as such:
var data = {message, link}
Thanks to chetan.
I have this Web Api call in my code behind. This is for my Single-Sign-On using Windows credential from our AD. What it did is just call the Web Api and check if the User is Authenticated and have access to the App.
I successfully call my Web Api using HttpClient.PostAsync but I'm wondering why it called several times in my Page_Load?
Please see below my Page_Load how I call the Web Api:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var languages = Language.Enabled().OrderByDescending(x => x.IsDefault);
var selected = languages.Where(x => x.Code == HSESA.Library.Helpers.Context.PublicLanguage().Code).Select(x => x.Code).FirstOrDefault();
Test();
}
}
And here is the Test() method and how I initialized HttpClient:
private static HttpClient client = new HttpClient();
protected void Test()
{
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string FromUrl = HttpContext.Current.Request.Url.AbsoluteUri;
#region Old Code
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Login", user));
postData.Add(new KeyValuePair<string, string>("FromUrl", FromUrl));
System.Net.Http.HttpContent content = new System.Net.Http.FormUrlEncodedContent(postData);
string url = "http://localhost:1899";
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync("/api/login/checkLogin", content).Result;
if (response.IsSuccessStatusCode)
{
LoginItemViewModel data = null;
string responseString = response.Content.ReadAsStringAsync().Result;
Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(responseString);
data = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginItemViewModel>(responseString);
}
#endregion
}
Thanks in advance to someone that can help me with my problem.
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