I am trying to ReplyAll to email with Outlook 365 API. Following this tutorial. As per tutorial to ReplyAll we just need to input Commnet but when I try to do that it's giving Bad Request error -
"error": {
"code": "ErrorInvalidRecipients",
"message": "At least one recipient isn't valid., A message can't be sent because it contains no recipients."
}
I am trying to do this with below method.
public string EmailReplyAll(AuthenticationResult result, string uriString, string msgBody)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uriString);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
EmailReplyAll replyAll = new EmailReplyAll();
replyAll.MsgBody = msgBody;
var jsonData = JsonConvert.SerializeObject(msgBody);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync(request.ToString(),content).Result;
if (!response.IsSuccessStatusCode)
throw new WebException(response.StatusCode.ToString() + ": " + response.ReasonPhrase);
uriString = response.Content.ReadAsStringAsync().Result;
return uriString;
}
Could someone please point me where I am doing wrong. I'm trying this with WPF.
Here is what I figured out and working for me.
EmailReplyAll class
public class EmailReplyAll
{
public string Comment { get; set; }
}
The URI string -
var uriString = String.Format(CultureInfo.InvariantCulture, "{0}api/{1}/me/messages/{2}/replyall", graphApiEndpoint, graphApiVersion, emailId);
//emailId is id of email e.g - AAMkADBjMGZiZGFACAAC8Emr9AAA=
EmailReplyAll method -
public string EmailReplyAll(AuthenticationResult result, string uriString, string msgBody)
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
EmailReplyAll replyAll = new EmailReplyAll();
replyAll.Comment = msgBody;
var jsonData = JsonConvert.SerializeObject(replyAll);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = httpClient.PostAsync(uriString, content).Result;
var apiResult = response.Content.ReadAsStringAsync().Result;
}
catch (Exception exception)
{
return "Error";
}
return apiResult;
}
Related
I am using HttpClient to call Microsoft Graph and create a new Team. I am using the Beta version.
string TeamsName = objTeam.TeamsName.ToString();
string TeamsDescription = objTeam.TeamsDescription.ToString();
var objJson = new CreateTeamsJson
{
templateodatabind = "https://graph.microsoft.com/beta/teamsTemplates(\'educationClass\')",
displayName = TeamsName,
description = TeamsDescription
};
var json = JsonConvert.SerializeObject(objJson, jsonSettings);
var modifiedjson = json.Replace("templateodatabind", "template#odata.bind");
StringContent postContent = new StringContent(modifiedjson, UnicodeEncoding.UTF8, "application/json");
if (!string.IsNullOrEmpty(TeamsName))
{
TokenHelper tokenHelper = new TokenHelper();
TokenResponse tokenResponse = tokenHelper.GetTokenAsync().Result;
using(HttpClient httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/beta/teams");
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", tokenResponse.access_token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = postContent;
var response = httpClient.SendAsync(request).Result;
var createdTeamDetails = response.Headers.Location;
if (response.IsSuccessStatusCode)
{
responseMessage = string.Format("Successfully created team - details: '{0}'", createdTeamDetails);
}
else
{
responseMessage = "ERROR: Failed to create Team.";
}
}
}
else
{
log.Info("Please provide Teams Name");
responseMessage = "Please provide Teams Name";
IsError = true;
}
When I run the code I am getting a 400 - Bad Rrequest at the following line:
var response = httpClient.SendAsync(request).Result;
I tried the same endpoint and same JSON body request in Graph Explorer and I could create teams successfully. Can anybody help me?
So I made a web API that authenticates with JSON Web Tokens, however, I haven't been able to authenticate using the HttpClient from my xamarin forms application. The odd thing is that I can connect without any problem on a console application that I made for testing, and both the console application and the xamarin forms app use almost exactly the same code.
The code in the console app is like this:
public static async Task<AutenticacionModel> PostCredentialsAsync(string UserName, string Password)
{
HttpClient cliente = new HttpClient();
cliente.BaseAddress = new Uri("http://172.25.1.53:9891");
HttpResponseMessage response = new HttpResponseMessage();
string _result = String.Empty;
try
{
string Path = cliente.BaseAddress + "oauth/secreto";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Path);
string autenticacion = "username=" + UserName + "&password=" + Password + "&grant_type=password";
request.Content = new StringContent(autenticacion, Encoding.UTF8, "application/x-www-form-urlencoded");
response = await cliente.SendAsync(request);
response.EnsureSuccessStatusCode();
_result = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
// something to do
}
return response.Content != null ? JsonConvert.DeserializeObject<AutenticacionModel>(_result) : new AutenticacionModel();
}
And the code in the Xamarin Forms:
public async Task<AutenticacionDTO> GetUsuario(string email, string clave)
{
string JSONAutenticacion;
HttpResponseMessage response = new HttpResponseMessage();
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(GlobalSetting.UrlWebApi);
string Path = client.BaseAddress + "oauth/secreto";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Path);
string autenticacion = "username=" + email + "&password=" + clave + "&grant_type=password";
request.Content = new StringContent(autenticacion, Encoding.UTF8, "application/x-www-form-urlencoded");
response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
JSONAutenticacion = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
string sss = ex.ToString();
return null;
}
return response.Content != null ? JsonConvert.DeserializeObject<AutenticacionDTO>(JSONAutenticacion) : new AutenticacionDTO();
}
When I use postman to connect to the web API that I have hosted in my local IIS, there's no problem, same with the console application. But whenever I try to connect with the Xamarin Forms App I get a 400 Bad Request response.
The code that makes the Jwt work goes like this:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = "*";
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
Seguridad _Seguridad = new fovissste.bll.Seguridad();
LoginDTO Usuario = _Seguridad.Login(context.UserName, context.Password).FirstOrDefault();
if (Usuario == null)
{
context.SetError("invalid_grant", "Usuario o contraseña incorrectos");
return;
}
ClaimsIdentity oauthIdentity = new ClaimsIdentity(new ApplicationUser(context.UserName, "JWT"), new[] { new Claim(ClaimTypes.Role, "Publico") });
var ticket = await Task.Run(() => new AuthenticationTicket(oauthIdentity, null));
context.Validated(ticket);
}
Can anybody help? Is this an issue with Xamarin Forms? I truly require some comments because I honestly can't see what I'm missing. I've read other posts in this site that suggest that it can be an issue of enabling remote requests on IIS or a CORS issue but I think that's handled in this line: context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
Try the following code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://172.25.1.53:9891");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string autenticacion = "?username=" + email + "&password=" + clave + "&grant_type=password";
HttpResponseMessage response = await client.PostAsync(client.BaseAddress + "oauth/secreto", new StringContent(autenticacion, Encoding.UTF8, "application/x-www-form-urlencoded"));
response.EnsureSuccessStatusCode();
string JSONAutenticacion = await response.Content.ReadAsStringAsync();
}
What is the value of Path after this line?
string Path = client.BaseAddress + "oauth/secreto";
Also try to add this line before using (var client... :
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
Edit
Changed
HttpResponseMessage response = await client.PostAsync(client.BaseAddress + autenticacion, new StringContent(autenticacion));
to
HttpResponseMessage response = await client.PostAsync(client.BaseAddress + "oauth/secreto", new StringContent(autenticacion, Encoding.UTF8, "application/x-www-form-urlencoded"));
I am trying to consume [this API] (https://learn.microsoft.com/en-us/rest/api/vsts/release/approvals/update). Below is my code, but i am getting 400 bad request.
HttpContent z = new StringContent("{\"status\": \"approved\",\"comments\": \"" + Request.QueryString["comment"].ToString() + "\"}", Encoding.UTF8, "application/json");
public static async Task PatchAsync(Uri requestUri, HttpContent content)
{
try
{
using (HttpClient client = new HttpClient())
{
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUri)
{
Content = content
};
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", "XXXXXXXXX"))));
//using (HttpResponseMessage response = await client.PostAsync(requestUri, content))
using (HttpResponseMessage response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
respApproval = responseBody;
}
}
}
catch (Exception ex)
{
respApproval = ex.ToString();
}
}
Since you only provide part of the code, I posted my code (which can update approvals successfully) below for your refernce:
public static async void ApproveRelease()
{
try
{
var username = "alternate auth or PAT";
var password = "password";
string accountName = "https://account.visualstudio.com";
string projectName = "projectname";
int approvalid = id;
var approveReleaseUri = "https://accountname.vsrm.visualstudio.com/projectname/_apis/release/approvals/approvlID?api-version=4.1-preview.3";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
var method = new HttpMethod("PATCH");
string approvveReleaseMetaData = "{\"status\":\"approved\", \"comments\":\"Good to go\"}";
var request = new HttpRequestMessage(method, string.Format(approveReleaseUri, accountName, projectName, approvalid, apiVersion))
{
Content = new StringContent(approvveReleaseMetaData, Encoding.UTF8, "application/json")
};
using (HttpResponseMessage response = client.SendAsync(request).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
By referring the blog Using ReleaseManagement REST API’s.
Note: you can only update a release approval which status is pending. If you try to update a release approval which approval status is approved or rejected, you will also get the 400 bad request response.
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
I have to post the multipart data to the server but I am getting below error
I am using the below code
public async static Task<string> HttpImagePostMethod(byte[] wInputData, string Uri, string path)
{
string result = string.Empty;
try
{
#region For Https (Secure) Api having SSL
var filter = new HttpBaseProtocolFilter();
filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
var client = new System.Net.Http.HttpClient(new WinRtHttpClientHandler(filter));
#endregion
MultipartFormDataContent requestContent = new MultipartFormDataContent();
// StreamContent content = new StreamContent(wInputData);
var content = new ByteArrayContent(wInputData);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
requestContent.Add(content, "file", path);
requestContent.Headers.Add("X-API-Key", UrlFactory.X_API_Key_Value);
requestContent.Add(new StringContent("144"), "type");
HttpResponseMessage aResp = await client.PostAsync(UrlFactory.BaseUrl + Uri, requestContent);
if (aResp.IsSuccessStatusCode)
{
result = await aResp.Content.ReadAsStringAsync();
}
else
{
result = await aResp.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
result = string.Empty;
}
return result;
}
I am getting error at this line
HttpResponseMessage aResp = await client.PostAsync(UrlFactory.BaseUrl + Uri, requestContent);
Due to this line
requestContent.Headers.Add("X-API-Key", UrlFactory.X_API_Key_Value);
Myself Answer this question maybe helpful to my other friends...
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new System.Uri(UrlFactory.BaseUrl + Uri);
httpRequest.Content = requestContent;
httpRequest.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
httpRequest.Headers.TryAddWithoutValidation("X-API-Key", UrlFactory.X_API_Key_Value);
Client(HttpClient) shouldn't contain any header, we declaring header in HttpRequestMessage
As the error message says, you're trying to set a header on the content but it doesn't belong there; your API token is a property of the request itself and not of its content.
Try adding that header to client.DefaultRequestHeaders instead.