How to set contributor role after creating a new azure subscription? - c#

I've created a new subscription using the microsoft CREST API with the following code:
WebClient client = new WebClient();
SATokenFormatReseller SA_Token = GetSAResellerToken();
client.Headers[HttpRequestHeader.Accept] = "application/json";
client.Headers[HttpRequestHeader.Authorization] = "Bearer " + SA_Token.access_token;
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers.Add("api-version", ApiVersion);
client.Headers.Add("x-ms-correlation-id", Guid.NewGuid().ToString());
client.Headers.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
var reqOrderObj = CreateReqOrderObject(service, mpn);
var reqOrderJson = JsonConvert.SerializeObject(reqOrderObj, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
string res = client.UploadString("https://api.cp.microsoft.com/" + TenantId + "/orders", "POST", reqOrderJson);
after creating successfully the subscription, I'm trying to set contributor role for the new subscription using the management azure core api, in this way:
public bool CreateRoleAssignment(string subscriptionId, string tenantId, string principalId)
{
bool roleGranted = false;
var azureToken = GetAzureAuthTokenForCustomerTenant(NativeClientId, PartnerCenterUser, PartnerCenterPassword, tenantId);
string responseContent = String.Empty;
var roleAssignmentId = Guid.NewGuid().ToString();
var correlationId = Guid.NewGuid().ToString();
var request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Authorization/roleAssignments/{1}?api-version=2015-07-01", subscriptionId, roleAssignmentId));
request.Method = "PUT";
request.Accept = "application/json";
request.ContentType = "application/json";
request.Headers.Add("x-ms-correlation-id", correlationId);
request.Headers.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
request.Headers.Add("Authorization", "Bearer " + azureToken.AccessToken);
string content = Json.Encode(CreateRoleAssignmentRequestData(subscriptionId, principalId));
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(content);
}
try
{
var response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
roleGranted = true;
}
}
catch (WebException webException)
{
using (var reader = new StreamReader(webException.Response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
roleGranted = false;
}
}
return roleGranted;
}
but the response is that the subscription does not exist.
After some time, if I run the same piece of code (CreateRoleAssignment), the role is given succesfully to the subscription.
How could I achive this process after creating the subscription?

As #GauravMantri said, using async polling as the sample code below.
var azureToken = GetAzureAuthTokenForCustomerTenant(NativeClientId, PartnerCenterUser, PartnerCenterPassword, tenantId);
string responseContent = String.Empty;
var roleAssignmentId = Guid.NewGuid().ToString();
var correlationId = Guid.NewGuid().ToString();
string url = string.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Authorization/roleAssignments/{1}?api-version=2015-07-01", subscriptionId, roleAssignmentId);
string content = Json.Encode(CreateRoleAssignmentRequestData(subscriptionId, principalId));
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
client.DefaultRequestHeaders.Add("x-ms-correlation-id", correlationId);
client.DefaultRequestHeaders.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + azureToken.AccessToken);
var response = await client.PutAsync(url, content);
while(!response.IsSuccessStatusCode)
{
response = await client.PutAsync(url, content);
}
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}

Related

How to get reviews from Trustpilot API

Attempting to get Trustpilot reviews from a specific product but cannot get anywhere.
Can get the token with success but then the reviews:
Querying https://api.trustpilot.com/v1/private/product-reviews/business-units/{businessUnitId}/reviews would return no results at all but runs without error
AND
Querying https://api.trustpilot.com/v1/product-reviews/business-units/{businessUnitId}/reviews would return an error "Microsoft.VisualStudio.Services.OAuth.AccessTokenResponseProduct review retrieved.{"fault":{"faultstring":"Invalid ApiKey","detail":{"errorcode":"oauth.v2.InvalidApiKey"}}}"
The ApiKey is the same to get the token so do not understand why does not work here. In a desperate attempt added the token to the url (?token={token}) and also not successful.
The sku collection includes all variants. Also tried without sku parameter and nothing is retrieved.
Here is the code:
var ApiKey = "ApiKey";
var SecretKey = "SecretKey";
var Username = "Username";
var Password = "Password";
var serverUrl = "xxx.xxx.xxx.xxx";
var BusinnessUnit = "BusinnessUnit";
var AuthUrl2 = "https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken";
var ReviewUrl = "https://api.trustpilot.com/v1/private/product-reviews/business-units/"+ bkBusinnessUnit + "/reviews";
var ProductReviewUrl = "https://api.trustpilot.com/v1/product-reviews/business-units/" + bkBusinnessUnit + "/reviews";
var token = "";
// get token
using (var httpClient = new HttpClient())
{
try
{
httpClient.BaseAddress = new Uri(AuthUrl2);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var authString = ApiKey + ":" + SecretKey;
string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encodedStr);
var stringPayload = "grant_type=password&username=" + Username + "&password=" + Password;
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(AuthUrl2, httpContent).Result;
var accessTokenResponseString = httpResponseMessage.Content.ReadAsStringAsync().Result;
var accessTokenResponseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(accessTokenResponseString);
token = accessTokenResponseObject.AccessToken;
Console.WriteLine("Token retrieved. " + token);
}
catch (Exception ex)
{
Console.WriteLine("Failed!" + ex.ToString());
}
}
// get product reviews
using (var httpClient = new HttpClient())
{
try
{
httpClient.BaseAddress = new Uri(ProductReviewUrl);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var authString = ApiKey + ":" + SecretKey;
string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encodedStr);
var stringPayload = "sku=SK40132-BLK-6,SK40132-BLK-8,SK40132-BLK-10,SK40132-BLK-12,SK40132-BLK-14,SK40132-BLK-16,SK40132-BLK-18&token=" + token;
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(ProductReviewUrl, httpContent).Result;
var reviewResponseString = httpResponseMessage.Content.ReadAsStringAsync().Result;
var reviewResponseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(reviewResponseString);
Console.WriteLine(reviewResponseObject + "Product review retrieved." + reviewResponseString);
}
catch (Exception ex)
{
Console.WriteLine("Failed!" + ex.ToString());
}
}
// get reviews
using (var httpClient = new HttpClient())
{
try
{
httpClient.BaseAddress = new Uri(ReviewUrl);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var stringPayload = "sku=SK40132-BLK-6,SK40132-BLK-8,SK40132-BLK-10,SK40132-BLK-12,SK40132-BLK-14,SK40132-BLK-16,SK40132-BLK-18";
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(ReviewUrl, httpContent).Result;
var reviewResponseString = httpResponseMessage.Content.ReadAsStringAsync().Result;
var reviewResponseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(reviewResponseString);
Console.WriteLine(reviewResponseObject + "Review retrieved." + reviewResponseString);
}
catch (Exception ex)
{
Console.WriteLine("Failed!" + ex.ToString());
}
}
/v1/private/product-reviews/business-units/{businessUnitId}/reviews endpoint requires token. It could be provided either via header or via query parameters. It works for you as you did it right.
/v1/product-reviews/business-units/{businessUnitId}/reviews endpoint only requires apikey. You could pass it in two ways:
via header
httpClient.DefaultRequestHeaders.Accept.Add("apikey", ApiKey);
via query parameters
var stringPayload = "sku=SK40132-BLK-6,SK40132-BLK-8,SK40132-BLK-10,SK40132-BLK-12,SK40132-BLK-14,SK40132-BLK-16,SK40132-BLK-18&apikey=" + ApiKey;
It was incredible simple it should be a GetAsync instead of a PostAsync.
Thanks anyway for looking at it.

How to fix The remote server returned an error: (403) Forbidden. dailymotion api

So I am using the Dailymotion API for uploading the video and use the code I get from the GitHub and it works perfectly but after 4 videos it gives the exception:
{"The remote server returned an error: (403) Forbidden."}
And I am getting an error in PublishVideo method
var response = request.GetResponse();
Main Code
var accessToken = GetAccessToken();
Authorize(accessToken);
Console.WriteLine("Access token is " + accessToken);
var fileToUpload = #"E:\Courses\[FreeCourseSite.com] Udemy - Entity Framework in Depth The Complete Guide\3. Building a Model using Database-First Workflow\11. Summary.mp4";
Console.WriteLine("File to upload is " + fileToUpload);
var uploadUrl = GetFileUploadUrl(accessToken);
Console.WriteLine("Posting to " + uploadUrl);
var response = GetFileUploadResponse(fileToUpload, accessToken, uploadUrl);
Console.WriteLine("Response:\n");
Console.WriteLine(response + "\n");
Console.WriteLine("Publishing video.\n");
var uploadedResponse = PublishVideo(response, accessToken);
Console.WriteLine(uploadedResponse);
Console.WriteLine("Done. Press enter to exit.");
Console.ReadLine();
}
private static UploadResponse GetFileUploadResponse(string fileToUpload, string accessToken, string uploadUrl)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
var responseString = Encoding.UTF8.GetString(responseBytes);
var response = JsonConvert.DeserializeObject<UploadResponse>(responseString);
return response;
}
private static UploadedResponse PublishVideo(UploadResponse uploadResponse, string accessToken)
{
var request = WebRequest.Create("https://api.dailymotion.com/me/videos?url=" + HttpUtility.UrlEncode(uploadResponse.url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", "OAuth " + accessToken);
var requestString = String.Format("title={0}&tags={1}&channel={2}&private={3}&published={4}",
HttpUtility.UrlEncode("123123123"),
HttpUtility.UrlEncode("tag1"),
HttpUtility.UrlEncode("news"),
HttpUtility.UrlEncode("true"),
HttpUtility.UrlEncode("true"));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
private static string GetAccessToken()
{
var request = WebRequest.Create("https://api.dailymotion.com/oauth/token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestString = String.Format("grant_type=password&client_id={0}&client_secret={1}&username={2}&password={3}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.Secret),
HttpUtility.UrlEncode(SettingsProvider.Username),
HttpUtility.UrlEncode(SettingsProvider.Password));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var oauthResponse = JsonConvert.DeserializeObject<OAuthResponse>(responseString);
return oauthResponse.access_token;
}
private static void Authorize(string accessToken)
{
var authorizeUrl = String.Format("https://api.dailymotion.com/oauth/authorize?response_type=code&client_id={0}&scope=read+write+manage_videos+delete&redirect_uri={1}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.CallbackUrl));
Console.WriteLine("We need permissions to upload. Press enter to open web browser.");
Console.ReadLine();
Process.Start(authorizeUrl);
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
Console.WriteLine("Press enter once you have authenticated and been redirected to your callback URL");
Console.ReadLine();
}
private static string GetFileUploadUrl(string accessToken)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var urlResponse = client.DownloadString("https://api.dailymotion.com/file/upload");
var response = JsonConvert.DeserializeObject<UploadRequestResponse>(urlResponse).upload_url;
return response;
}
}
It could be related to many causes. I suggest you to catch the error and get the response stream from our API:
try{
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
catch(WebException e){
var rs = e.Response.GetResponseStream();
string errorResponseString;
using (var reader = new StreamReader(rs))
{
errorResponseString = reader.ReadToEnd();
}
Console.WriteLine(errorResponseString);
return null;
}
You will get a message explaining you why your access is forbidden.
I also invite you to check our API rate limit rules which can be a cause of forbidden call: https://developer.dailymotion.com/api/#rate-limit

Refactor HttpWebRequest to HttpClient?

How would I convert this to HttpClient? What I'm looking to do is submit a Tweet to the Twitter api and get the response as Json. The HttpWebRequest is working fine but I just want to port it to HttpClient. I made an attempt at it in the second code example, but it's not actually sending or receiving the response.
HttpWebRequest request = null;
WebResponse response = null;
string responseCode = String.Empty;
try
{
string postBody = "status=" + EncodingUtils.UrlEncode(status);
request = (HttpWebRequest)HttpWebRequest.Create(resource_url);
request.ServicePoint.Expect100Continue = true;
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
request.ServicePoint.ConnectionLimit = 1;
request.Headers.Add("Authorization", authHeader);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(postBody);
}
}
using (response = request.GetResponse())
{
response.ContentType = "application/json";
responseCode = ((HttpWebResponse)response).StatusCode.ToString();
}
}
catch (WebException ex)
{
if (ex.Status != WebExceptionStatus.NameResolutionFailure)
{
request.Abort();
request = null;
}
throw ex;
}
return responseCode;
This is what I've tried to get it work:
private async Task<string> MakeWebRequest1(string status, string resource_url, string authHeader)
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.Credentials = CredentialCache.DefaultCredentials;
clientHandler.PreAuthenticate = true;
clientHandler.AllowAutoRedirect = true;
string responseCode = "";
string postBody = "status=" + EncodingUtils.UrlEncode(status);
var request = new HttpRequestMessage()
{
RequestUri = new Uri(resource_url),
Method = HttpMethod.Post,
};
request.Headers.Add("Authorization", authHeader);
// request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
request.Content = new StringContent(postBody, Encoding.UTF8,"application/x-www-form-urlencoded");//CONTENT-TYPE header
using (HttpClient client = new HttpClient(clientHandler))
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
// Stream stuff = await client.GetStreamAsync(resource_url);
using (HttpResponseMessage response = await client.SendAsync(request))
{
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if(response.StatusCode == HttpStatusCode.OK)
{
responseCode = "OK";
}
}
}
clientHandler.Dispose();
return responseCode;
}
enter code here
I've tried to add another parameter to the request and it's always coming back as 401 unauthorized. I'm trying to create a Twitter thread. If I remove the in_reply_to_status_id then it's fine.
data = new Dictionary<string, string> {
["status"] = "#username + status,
["in_reply_to_status_id"] = "1167588690929115136"
};
The Twitter API describes it here https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
Reference You're using HttpClient wrong to understand why a static client is being used.
static Lazy<HttpClient> client = new Lazy<HttpClient>(() => {
HttpClientHandler clientHandler = new HttpClientHandler {
Credentials = CredentialCache.DefaultCredentials,
PreAuthenticate = true,
AllowAutoRedirect = true
};
return new HttpClient(clientHandler);
});
private async Task<string> PostStatusRequestAsync(string status, string resource_url, string authHeader) {
using (var request = new HttpRequestMessage(HttpMethod.Post, resource_url)) {
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new Dictionary<string, string> {
["status"] = status
};
request.Content = new FormUrlEncodedContent(data);
using (HttpResponseMessage response = await client.Value.SendAsync(request)) {
return response.StatusCode.ToString();
}
}
}
Note the use of the FormUrlEncodedContent for the request body, which will encode and concatenate the data as well as take care of the mime type header
...but it's not actually sending or receiving the response.
Ensure that the above is not invoked as a synchronous blocking call, like .Result, which could cause a deadlock.
For example, an async event handler can be used to make the async call
public async void onButtonClick(object sender, EventArgs args) {
//Non-blocking call
var tweetRequestCode = await PostStatusRequestAsync(TweetText, AuthUtils.GetResourceUrl(), AuthUtils.GetWebRequestHeader()));
//back on UI thread
//...
}
Reference Async/Await - Best Practices in Asynchronous Programming

Web API Authorization via HttpWebRequest

I have a function to call my Web API. It works well if TestCallingRemotely is set to [AllowAnonymous].
var httpWebRequest = (HttpWebRequest)WebRequest.Create(
"http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
string input = "{}";
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
How do I pass the username and password to the HttpWebRequest for authorization?
I need to call my Web API from CLR integration, which only supports System.Net.
ABP's startup template uses bearer token authentication infrastructure.
var token = GetToken(username, password);
// var httpWebRequest = (HttpWebRequest)WebRequest.Create(
// "http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
// httpWebRequest.ContentType = "application/json";
// httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
// ...
Get token
This uses a crude way to extract the token, inspired by an MSDN article.
private string GetToken(string username, string password, string tenancyName = null)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(
"http://localhost:6334/api/Account/Authenticate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var input = "{\"usernameOrEmailAddress\":\"" + username + "\"," +
"\"password\":\"" + password + "\"}";
if (tenancyName != null)
{
input = input.TrimEnd('}') + "," +
"\"tenancyName\":\"" + tenancyName + "\"}";
}
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string response;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
// Crude way
var entries = response.TrimStart('{').TrimEnd('}').Replace("\"", String.Empty).Split(',');
foreach (var entry in entries)
{
if (entry.Split(':')[0] == "result")
{
return entry.Split(':')[1];
}
}
return null;
}
If the server uses basic authentication you can add the header like this:
var httpWebRequest = (HttpWebRequest) WebRequest.Create(
"http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var username = "Aladdin";
var password = "opensesame";
var bytes = Encoding.UTF8.GetBytes($"{username}:{password}");
httpWebRequest.Headers.Add("Authorization", $"Basic {Convert.ToBase64String(bytes)}");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string input = "{}";
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

Xamarin Forms Json Service Insert Data

I want to add a record to the json service in my application. How can I do this via Service Url. Here is my code.
CustomerModel customer = new CustomerModel();
customer.Name = entryCompanyName.Text;
customer.Title = entryCompanyTitle.Text;
customer.PhoneNumber = entryTelephone.Text;
customer.FaxNumber = entryFax.Text;
customer.Email = entryEmail.Text;
customer.CityId = 6444;
string json = JsonConvert.SerializeObject(customer);
string sContentType = "application/json";
string path = "service url";
HttpClient Client = new HttpClient();
var task = Client.PostAsync(path, new StringContent(json.ToString(), Encoding.UTF8, sContentType));
I'm trying M. Wiśnicki's solution, but I took this error
I did not get an error when I added System.net :( Where do i make mistakes?
This worked for me
public static async Task<string> PostEntityToApi<T>(string yourMethodUrl, T yourModel)
{
try
{
if (_httpClient == null)
{
_httpClient = new HttpClient { BaseAddress = new Uri(yourWebSiteUrl) };
}
var stringContentInput = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(new Uri(yourWebSiteUrl. + apiUrl), stringContentInput);
if (!response.IsSuccessStatusCode)
{
throw new Exception(response.StatusCode.ToString());
}
var stringAsync = await response.Content.ReadAsStringAsync();
LoggingManager.Error("Received error response: " + stringAsync);
return stringAsync;
}
catch (Exception exception)
{
return null;
}
}
You can use WebRequest, this sample working for me, i use it in my app.
This is System.Net.WebRequest class, here you find doc.
public async Task<string> PostSample(object data, string uri)
{
// Create an HTTP web request using the URL:
var request = (HttpWebRequest) WebRequest.Create(new Uri(uri));
request.ContentType = "application/json";
request.Method = "POST";
var itemToSend = JsonConvert.SerializeObject(data);
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
streamWriter.Write(itemToSend);
streamWriter.Flush();
streamWriter.Dispose();
}
// Send the request to the server and wait for the response:
using (var response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream);
var message = JsonConvert.DeserializeObject<string>(reader.ReadToEnd());
return message;
}
}
}

Categories

Resources