How can I use the access token to get a list of projects from a website in c#? - c#

I am trying to create a C# console application to download project details from a website which supports REST OAuth 2.0. How do I make a request/response call to the website using the Access Token?
Here is my code:
public string token = "4bjskfa2-b37d-6244-8413-3358b18c91b6";
public async Task GetProjectsAsync()
{
try
{
HttpClient client = new HttpClient();
var projects = "https://app.rakenapp.com/api/v2/projects?" + token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(projects);
if (output.IsSuccessStatusCode)
{
string response = await output.Content.ReadAsStringAsync();
project proj = JsonConvert.DeserializeObject<project>(response);
if (proj != null)
{
Console.WriteLine(proj.name); // You will get the projects here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}

you need to add a header to your request:
string url = "https://app.rakenapp.com/api/v2/projects";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
HttpResponseMessage response = await httpClient.GetAsync(url);
var contents = await response.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<project>.contents);
return model;
}

Related

Azure Speech API gets into an endless loop when called inside a custom WebAPi

Let me explain the scenario -
I have a custom web API created for an application which has multiple parameters, the user call this api by passing multiple parameters which are concatenated based on some logic and then inside this custom api it calls Azure speech API to convert Text to Speech (in 2 steps - 1. I call the Azure speech service to get the token, 2. I call the Azure speech service to convert the text to speech)
The problem -
When I call the Azure speech service to fetch the token, it stays in a endless loop.
Below is the sample code, any pointers in right direction will be helpful -
public class ConverterController : ApiController
{
/// <summary>
/// default constructor
/// </summary>
public ConverterController()
{
}
[HttpGet]
public HttpResponseMessage ConvertUsingSpeech([FromUri] OutReachMessage outReachMessage)
{
try
{
outReachMessage = new OutReachMessage();
var result = ConvertUsingSpeechApi(outReachMessage);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(OutputMp3FilePath);
return response;
}
catch (Exception ex)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
async Task ConvertUsingSpeechApi(OutReachMessage outReachMessage)
{
var authObj = new Authentication("key");
var token = authObj.GetAccessToken();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", token);
client.DefaultRequestHeaders.Add("Content-Type", contentType);
client.DefaultRequestHeaders.Add("X-Microsoft-OutputFormat", outputFormat);
UriBuilder uriBuilder = new UriBuilder(fetchSpeechUri);
var content = new StringContent("<speak version='1.0' xml:lang='hi-IN'><voice xml:lang='hi-IN' xml:gender='Female' name = 'hi-IN-SwaraNeural'>" +
"Welcome mahesh to the world of Azure - feeling great. </voice></speak>",
Encoding.UTF8, "text/xml");
var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, content);
using (var response = client.PostAsync(uriBuilder.Uri.AbsoluteUri, content).Result)
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
string fileToWriteTo = OutputMp3FilePath;
using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
{
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
}
}
}
}
authentication class - which fetchs the token
public class Authentication
{
public static readonly string FetchTokenUri =
"https://centralindia.api.cognitive.microsoft.com/sts/v1.0/issueToken";
private string subscriptionKey;
private string token;
public Authentication(string subscriptionKey)
{
this.subscriptionKey = subscriptionKey;
this.token = FetchTokenAsync(FetchTokenUri, subscriptionKey).Result;
}
public string GetAccessToken()
{
return this.token;
}
private async Task<string> FetchTokenAsync(string fetchUri, string subscriptionKey)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
UriBuilder uriBuilder = new UriBuilder(fetchUri);
var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, null);
Console.WriteLine("Token Uri: {0}", uriBuilder.Uri.AbsoluteUri);
return await result.Content.ReadAsStringAsync();
}
}
}
Note - I am able to call the Azure Speech api with postman and also with console application, only when I call the azure service inside my custom webapi it doesnot works.
Change code like below, delete string subscriptionKey. It will work.
public Authentication()
{
this.subscriptionKey = subscriptionKey;
this.token = FetchTokenAsync(FetchTokenUri, subscriptionKey).Result;
}

Unable to send string as HTTPContent

I have created an API, which shall have the capability to connect to en external API via POST and with a request body in form of a string.
I am able to connect directly to the API from Postman without trouble.. But it does not work via my own API.
Any ideas?
This is the Pastebin.
private string EncodeExternalApiLink = "https://blabla.dk";
private string EncodeExternalApiLinkPostFilter = "searchstring/blabla/api/search";
[HttpPost("getdata/filtered")]
public async Task<IActionResult> GetDataFromExternalFiltered([FromBody] string filter)
{
var filterString = new StringContent(filter);
EncodeExternalToken token = GetExternalToken().Result;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(EncodeExternalApiLink);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token);
using (var response = await client.PostAsync(EncodeExternalApiLinkPostFilter, filterString))
{
return Json(response);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return Content(content, "application/json");
}
else
{
return NotFound();
}
}
}
}
Salutations. You might need to add a "/" to the end of your base address EncodeExternalApiLink or to the beginning of EncodeExternalApiLinkPostFilter.

Can't upload large files using MVC.NET Core application

I have an issue uploading large files in the MVC.NET Core application. No matter what I do I get back a 404 no data response
Here is my task method that uploads file
[RequestSizeLimit(40000000)]
public static async Task<string> UploadAttachment(string bis232JsonString, string url, string formType, string token, long maxResponseContentBufferSize)
{
var result = "Error";
try
{
// To Do : Use ConfigurationManager.AppSettings["endpoint"];
string endpoint = $"{url}/{formType}Attachment/post";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.MaxResponseContentBufferSize = maxResponseContentBufferSize;
using (var request = new HttpRequestMessage(HttpMethod.Post, endpoint))
{
request.Content = new StringContent(bis232JsonString, Encoding.UTF8, "application/json");
using (var response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode && (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent))
result = "Success";
else
result = "Error";
}
}
}
}
catch (Exception ex)
{
//to do : Log application error properly
result = "Error";
}
return result;
}
I tried the following
Tried to use MaxResponseContentBufferSize property of HTTP Client
Tried to use [RequestSizeLimit(40000000)] decorator
Tried to use [DisableRequestSizeLimit] decorator
Tried to update the upload limit globally as shown below
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = 52428800; });
However, no matter what I try to do, nothing seems to work
Please let me know if there is anything that could be done to make it work

Xamarin.Forms HTTP Post to Web Service - 404 Error

Sorry if this question has been asked already but I can not seem to find one that relates to my issue. I have a web service built using C# Asp.Net Web API, here I have the following POST method:
[HttpPost]
[Route("AddLocation")]
public void PostLocation(Locations model)
{
using (Entities db = new Entities())
{
C_btblFALocation newLocation = new C_btblFALocation()
{
cLocationCode = model.Code,
cLocationDesc = model.Description
};
db.C_btblFALocation.Add(newLocation);
db.SaveChanges();
}
}
In my Xamarin.Forms project I have my Rest Service Class:
public async Task SaveLocationAsync(Locations item)
{
var uri = new Uri(string.Format(Constants.LocationSaveRestUrl));
try
{
var json = JsonConvert.SerializeObject(item);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(#" Location successfully added.");
}
else
{
Debug.WriteLine(#" Oops, there seems to be a problem.");
}
}
catch (Exception ex)
{
Debug.WriteLine(#" ERROR {0}", ex.Message);
}
}
And my URL is set in my Constants class:
public static string LocationSaveRestUrl = "http://172.16.124.18/ArceusService/api/Assets/AddLocation/";
The problem is I keep getting a 404 error. I have tried every way I can think of to set the URL but no luck. The data seems to be passed through fine from debugging but I don't know how the URL should be for a POST method?
Thanks for any help!
How is your client variable declared? Usually you set a BaseAddress and in your Get/PostAsync you only set the actual resource URI.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}

How to sent data with restfull web service in C#

I m developing a Windows Phone 8.1 Application.
I'm newbie in C# and WP. I used restfull web services for sql server connection but i can't send data to server. I had an error message as "Bad Request".
This is my login page code bihend
KullaniciManager km = new KullaniciManager();
km.Login();
HttpClient httpClient = new System.Net.Http.HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:3577/KullaniciService.svc/Login");
HttpResponseMessage response = await httpClient.SendAsync(request);
MessageDialog msgbox = new MessageDialog("Serverdan gelecek hata mesajı");
await msgbox.ShowAsync();
My BLL code is here.
public LoginResponse KullaniciKontrolEt(string kulAdi, string sifre)
{
LoginResponse response = null;
using (NeydiolilacEntities noi = new NeydiolilacEntities())
{
object data = noi.ta_Kullanici.Where(x => x.Kul_Ad == kulAdi && x.Kul_Sifre == sifre && x.Kul_Statu == true).SingleOrDefault();
response = new LoginResponse()
{
Data = data
};
return response;
}
Thanks for your help :)
*
Hi Asim,
This will help you I hope
Note : Code for Win8.1
public async Task<string> GeneralRequestHandler(string RequestUrl, object ReqObj)
{
try
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(ReqObj);
HttpContent content = new StringContent(json);
Windows.Web.Http.IHttpContent c = new Windows.Web.Http.HttpStringContent(json);
c.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/json");
Windows.Web.Http.Filters.HttpBaseProtocolFilter aHBPF = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
aHBPF.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
aHBPF.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName);
string responseText;
using (var handler = new Windows.Web.Http.HttpClient(aHBPF))
{
Windows.Web.Http.HttpResponseMessage r = await handler.PostAsync(new Uri(RequestUrl), c);
responseText = await r.Content.ReadAsStringAsync();
}
}
catch (HttpRequestException ex)
{
}
return responseText;
}
*

Categories

Resources