how can I set up an HTTP call in asp.net core mvc
$url = "https://prod-25.northeurope.logic.azure.com:443/..."
$parms = #{
Uri = $url
Method = 'post'
ContentType = 'application/json'
body = '{"recipient": "stefan.","body":"Test"}'
}
curl #parms
using
using System.Net.Http;
and your code will be
var url = "http://yoursite.com/Home/Insert";
var data = new {"recipient"= "stefan.", "body"="Test"};
using(var client = new HttpClient())
{
var response = await client.PostAsJsonAsync(url, data);
string responseContent = await response.Content.ReadAsStringAsync(); // only to see response as text ( debug perpose )
var result = await ProcessedResult<TResult>(response); // cast it to TResult or any type that you expect to retrieve
}
Related
I've created a public Data Entity in dynamics with the following fields:
I keep getting a bad request response, but I'm not sure why.
I've tried to make a POST request in two ways:
1.
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionStatus = "Created" };
string jsonMessage = JsonConvert.SerializeObject(hireAction);
using (HttpClient client = new HttpClient())
{
HttpRequestMessage requestMessage = new
HttpRequestMessage(HttpMethod.Post, "MyDynamicsEnvironmentName/data/HireActions?cross-company=true");
requestMessage.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("Authorization", AuthResult.AuthorizationHeader);
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Logic
}
}
var url = "MyDynamicsEnvironmentName/data/HireActions?cross-company=true";
var req = HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers["Authorization"] = AuthResult.AuthorizationHeader;
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionId = "12345", HireActionStatus = "Created" };
var jsonSettings = new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
var postString = "CompanyName='DEMF'" + "&MovieId='DEMF-000000014'" + "&HireActionId=132&HireActionStatus='Created'";
var data = JsonConvert.SerializeObject(postString, jsonSettings);
var bytes = Encoding.Default.GetBytes(postString);
var newStream = req.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
using (var resp = req.GetResponse())
{
var results = new StreamReader(resp.GetResponseStream()).ReadToEnd();
}
Some keypoints:
-Of course you'd replace MyDynamicsEnvironmentName with the URL for the environment. The URL is correct and verified however, by the fact that GET requests do work
-The Authresult.AuthorizationHeader contains a valid token, also validated by working GET requests
As said before, both of these result in a bad request. Does someone know what is wrong or missing?
The code below gets a token which I then use to try and fetch some data from an API which is behind AzureAD authentication.
I get a token back, but when I use it to try and reach the API, I get "login to your account" in apiResponse.
What is wrong with my authorization?
var recoAadAppId = "xxxxxxxxxxxxxx";
var callerAadAppId = "xxxxxxxxxxxxxx";
var callerAadTenantId = "xxxxxxxxxxxxxx";
var token = await AcquireTokenWithSecret(callerAadAppId, callerAadTenantId, recoAadAppId);
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(token.CreateAuthorizationHeader());
using (var response = await httpClient.GetAsync("https://redacted/app/rest/buildQueue"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
}
public static Task<AuthenticationResult> AcquireTokenWithSecret(
string callerAadAppId, string callerTenantId, string recoAadAppId)
{
var secret = "mysecret";
var app = ConfidentialClientApplicationBuilder.Create(callerAadAppId).WithAuthority($"https://login.microsoftonline.com/{callerTenantId}").WithClientSecret(secret).Build();
var scopes = new[] { $"{recoAadAppId}/.default" };
return app.AcquireTokenForClient(scopes).ExecuteAsync(CancellationToken.None);
}
I am trying to use the Dynamics 365 Web API to GET records. The fetch query generated is too long to use a normal GET query so a workaround is to POST the request instead.
I have simplifed the fetch statement here for ease.
Ignore the lack of async/await and use of .Result, that can easily be sorted afterwards.
Code:
var clientcred = new ClientCredential(Config.ClientId, Config.ClientSecret);
var authenticationContext = new AuthenticationContext($"{Config.AadInstance}{Config.TenantId}");
var authenticationResult = authenticationContext.AcquireTokenAsync(Config.DynamicsUrl, clientcred).Result;
var token = authenticationResult.AccessToken;
var client = new HttpClient();
client.BaseAddress = new Uri("https://foobar.crm4.dynamics.com");
client.Timeout = new TimeSpan(0, 2, 0);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/data/v9.1/$batch");
var content = "--batch_rob--\n" +
"Content-Type: application/http\n" +
"Content-Transfer-Encoding: binary\n" +
$"GET {Config.BaseUrl}contacts?fetchXml=<fetch count=\"10\" ><entity name=\"contact\" ><attribute name=\"fullname\" /></entity></fetch> HTTP/1.1\n" +
"OData-Version: 4.0\n" +
"OData-MaxVersion: 4.0\n" +
"--batch_rob--";
using (var content2 = new MultipartContent())
{
content2.Add(new StringContent(content));
content2.Headers.Remove("Content-Type");
content2.Headers.TryAddWithoutValidation("Content-Type", "multipart/mixed;boundary=batch_rob");
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/data/v9.1/$batch")
{
Content = content2
};
var response = client.SendAsync(request).Result;
var outcome2 = response.Content.ReadAsStringAsync().Result;
}
This all compiles and appears to run fine. The response however does not contain the JSON I expect (the result of the GET query) but rather is just:
--batchresponse_20851dc6-4ff6-4914-a749-66f451985f67--
Any idea what I have missed?
This is based on the example demonstrated here:
https://dreamingincrm.com/2017/01/15/executing-large-fetchxml-with-webapi/
I have a 3rd party API as shown in below image.
I'm trying to call this API in ASP.Net MVC controller as below:
public ActionResult GetQuickCatalogueAsync(string category = "f97b9ec8-5e74-4f20-8582-471d067fc6c4")
{
using (var client = new HttpClient())
{
var data = JsonConvert.SerializeObject(new
{
Content = new { categoryId = category },
Key = "test",
Name = "get-products"
});
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
var res = client.PostAsync(_baseUrl, content).Result.Content.ReadAsStringAsync().Result;
var response = JsonConvert.DeserializeObject<Product>(res);
return Content("");
}
}
The PostAsync is not getting Payload body (content) properly here.
Generated data object:
{"content":{"categoryId":"f97b9ec8-5e74-4f20-8582-471d067fc6c4"},"key":"test","name":"get-products"}
Expected:
{"Name":"get-products","Key":"test","Content":"{ \u0022categoryId\u0022:\u0022f97b9ec8-5e74-4f20-8582-471d067fc6c4\u0022}"}
And the Error on Post
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-d1fb352d7eb19d4cbdb542bc7cee59fb-e62da6de34faee4b-00","errors":{"$.content":["The JSON value could not be converted to System.String. Path: $.content | LineNumber: 0 | BytePositionInLine: 12."]}}
My Web API is receiving null value in Httpclient PostAsJsonAsync:
public static async Task<DefaultApiResponse<T>> PostList<T>(string url, string token, List<AddEventViewModel.Agenda> request)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
var content = JsonConvert.SerializeObject(request);
var buffer = System.Text.Encoding.UTF8.GetBytes(content);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var httpResponse = await client.PostAsJsonAsync(url, byteContent);
var defaultresponse = JsonConvert.DeserializeObject<DefaultApiResponse<T>>(await httpResponse.Content.ReadAsStringAsync());
return defaultresponse;
}
Why?
I would try posting as a StringContent object instead
var content = new StringContent(
JsonConvert.SerializeObject(request),
Encoding.UTF8,
"application/json");
defaultresponse = await client.PostAsync(url, content);