MS Graph API returns 400 Bad request - c#

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?

Related

Postman form-data: How to program it inside a HttpRequestMessage?

I am doing a request through postman to a specific url but I set the form-data type in order to get data to the site like this:
Now I want to program this request inside C# but everything I tried so far is returning a 400 Bad Request response. This is what I tried:
public async Task<CheckAccessTokenModel> CheckAccessTokenAsync(string accessToken)
{
string uriString = "someurl";
var uri = new Uri(uriString);
try
{
using(var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri
};
var ClientId = ConfigurationAccessor.Configuration["WebCredentials:ClientId"];
var Secret = ConfigurationAccessor.Configuration["WebCredentials:Secret"];
var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{ClientId}:{Secret}"));
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent("token"), accessToken);
request.Content = content;
var response = await httpClient.SendAsync(request);
var checkTokenResponseData = await response.Content.ReadAsStringAsync();
//return new CheckAccessTokenModel { Active = true, Exp = 1647431224233 };
return JsonConvert.DeserializeObject<CheckAccessTokenModel>(checkTokenResponseData);
}
}
catch
{
return null;
}
}
I am doing it with the MultipartFormDataContent Object as suggested by many others here but it still won't work.
What can be the problem here?
EDIT: Wrong picture replaced
You can simply
request.Content = new StringContent($"token={accessToken}");
With form data I think it's something like this:
var data = new Dictionary<string, string>
{
{"token", acccessToken}
};
using var content = new FormUrlEncodedContent(data);
request.Content = content;

Why always get Bad Request in my C# console application Dynamics 365 Business Central Webservice

https://api.businesscentral.dynamics.com/v2.0/{tenantId}/{CompanyName}/ODataV4/Company('SimpleCompany')/TransferOrder
Service Name : "TransferOrder"
Object Name : Transfer Order
try
{
var url = $"https://api.businesscentral.dynamics.com/v2.0/{tenantId}/{companyName}/ODataV4/Company('{simplecompany}')/TransferOrder";
var client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
TransferOrderHeader hdr = new TransferOrderHeader();
hdr.No = "T-002";
hdr.Transfer_from_Code = "WH1";
hdr.Transfer_to_Code = "Van1";
hdr.Direct_Transfer = true;
hdr.In_Transit_Code = "";
hdr.Posting_Date = "2022-05-23";
hdr.Shipment_Date = "2022-05-24";
string json = JsonConvert.SerializeObject(hdr);
StringContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, httpContent);
var content = await response.Content.ReadAsStringAsync();
var jObj = JObject.Parse(content);
if (response.StatusCode.ToString() == "Created")
{
}
}
catch (Exception ex)
{
throw new ArgumentException(ex.Message);
}
**Why Always Come Bad Request Error, Postman also badrequest if I add Transfer_from_Code, Transfer_to_Code Fields Value and Direct_Transfer : true, but if I add Transfer_from_Code : "" Transfer_to_Code : "", Direct_Transfer : false then postman and my program both working fine with success response. **
{"error":{"code":"Unknown","message":"Property \"Editable\" for Transfer-from Code is invalid. Expression: [( Status = 0 ) AND p5740p5740EnableTransferFields] CorrelationId: xxx76d22-ff59-4251-aa7d-xxfe21fc0cbx."}}

I have an issue with Authorization to consume external service in C#

When I consume the service using RestClient it's working fine but when I consume it using HttpClient get these errors "Missing authorization" or "Unhandled Exception"
RestClient
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", token);
request.AlwaysMultipartFormData = true;
request.AddParameter("business_branch_id", "3");
request.AddParameter("dropoff_address_line", "Remal str. test address line");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
HttpClient
using (var request = new HttpRequestMessage(HttpMethod.Post, url))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//if i use this i get this error "Missing authorization"
//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
//if i use this i get this error Unhandled Exception
request.Headers.Add("Authorization", token);
using (var streamContent = new StreamContent(memoryContentStream))
{
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = streamContent;
var response = _httpClient.SendAsync(request);
var createdContent = response.Result.Content.ReadAsStringAsync();
orderResponse = JsonConvert.DeserializeObject<OrderResponse>(createdContent.Result);
orderResult = GetOrderResult(orderResponse);
}
}

How to send POST request to outlook 365 API to ReplyAll

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;
}

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

Categories