I created a Web API (Server) project in ASP.Net Core. Testing it with Postman is successful. Consuming the Web API from an ASP.Net Core Blazor (Client) project is also successful. I was able to display the JSon result in the Razor pages without problems. However, when I created a client project in Xamarin.Forms, I wasn't able to successfully get the JSon results but it gives me an "Error occurred while sending request" and an "InnerException "The text associated with this error code could not be found. The certificate authority is invalid or incorrect". The code I used to consume the API is below:
public async Task<List<Contact>> GetAllDataAsync()
{
var Contacts = new List<Contact>();
var uri = new Uri(string.Format(Constants.ContactsUrl, string.Empty));
try
{
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Contacts = JsonConvert.DeserializeObject<List<Contact>>(content);
}
}
catch (Exception ex)
{
Debug.WriteLine(#"\tERROR {0}", ex.Message);
}
return Contacts;
}
What else did I miss?
Related
I am building back-end(API) of mobile application on asp.net core. Using swagger for visualization of API calls and so on. Currently I am creating external authentications, I have some problems with LinkedIn.
The structure of application is simple, mobile side gets LinkedIn user's Access Token and sends it to me with API request, I have to request user data from LinkedIn by received Access Token, register or login him/her and return response to mobile side.
There is the code below, and commented links where I tried to send requests.
public async Task<IResponse<LinkedInAuthenticationResponse>> LinkedInAuthentication(string accessToken)
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.DefaultRequestHeaders.Add("x-li-format", "json");
var oauthUrl = "https://api.linkedin.com/v1/people";
// https://api.linkedin.com/v2/me
// https://api.linkedin.com/v1/people/~:(id,formatted-name,email-address,picture-url)
var response = httpClient.GetAsync(oauthUrl).Result;
string responseContent = string.Empty;
try
{
responseContent = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
return Ok(JsonConvert.DeserializeObject<GoogleAuthenticationResponse>(responseContent));
}
catch (Exception ex)
{
}
}
}
The problem is that LinkedIn doesn't provide exact link where API call should be send, I had to try several of them but the response is always 401.
My Access Token is valid, this can not be problem. I have used almost same code for Facebook and Google and they work perfectly.
Any one can provide link which works for API calls ?
This issue has nothing to do with the asp.net framework but with the endpoint, you are using. Since v1 of the LinkedIn API has been deprecated, you need to change your endpoint as for this link here
I've created a API where I want to call another API from, for testing im using Pokemon API with PostMan. However when I want to call this API im my own API application getting an error. Code executed when API is getting called:
[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
[System.Web.Http.Route("RedirectApi")]
public async Task<object> getCall()
{
checkAuthorisation();
setVariables();
if (isAuthorized == true)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://pokeapi.co/api/v2/pokemon/ditto/");
var code = response.StatusCode;
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(responseBody);
}
else
{
return JsonConvert.DeserializeObject("Unauthorized");
}
}
Im calling my API with this link:
http://localhost:54857/GetPokemon
Whenever I execute this using Postman in debug mode it executes but fails on this code:
HttpResponseMessage response = await client.GetAsync("https:/pokeapi.co/api/v2/pokemon/ditto/");
It also does not give me any feedback except what Postman gives me back:
Hope someone can help!
Thanks in advance!
I have followed the following tutorial
Azure AD B2C: Call an ASP.NET Web API from an ASP.NET Web App
I am able to run the app.
When the authorisation code is received I put a break point on line var code = notification.Code;and I am able to see all the claims received.
But when I try to print the claims nothing is displayed and the app exits. It shows a null object reference on the following line
string a = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Country).Value;
Any idea how I can print all the claims. Any help will be appreciated. Thank you
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
// Extract the code from the response notification
var code = notification.Code;
string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
string a = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Country).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null);
try
{
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes);
}
catch (Exception ex)
{
//TODO: Handle
throw;
}
}
I'm trying to access the Azure Elastic Scale Split/Merge tool from an ASP.NET application. I can open the page in my browser after I use the certificate that I uploaded on Azure. But when I try to connect to the page in ASP.NET I keep getting 500 Internal Server Error, even though I used the certificate in my request.
Is there something wrong with the code below? Have I been forgetting something?
var handler = new WebRequestHandler();
handler.ServerCertificateValidationCallback = delegate { return true; };
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(Cert); //Cert is the X509Certificate2 I use
using (var client = new HttpClient(handler))
{
try
{
var response = await client.GetAsync(Endpoint); //Endpoint = https://foobar.cloudapp.net/
if (response.IsSuccessStatusCode)
{
var a = response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
Found where I went wrong. When creating the Certificate I was using the .cer file, but it works now with the .pfx file
I am trying to connect to Http Service using flex wizard
The server side is Asp.net MVC4 Web Api, I used the templates to create simple CRUD controller.
The problem is that test operation gives back: "InvocationTargetException:The URL is not valid" error message. I have seen that the problem is the http response status. If it is OK 200 then I dont have that problem. I can change the response status manually to OK in the controller, but why Flex cannot handle the default 204 response status from controller template?
This is the function from the server controller:
public HttpResponseMessage Postattributes(attributes attributes)
{
if (ModelState.IsValid)
{
db.attributes.Add(attributes);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, attributes);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = attributes.attId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
if I change to HttpStatusCode.OK I do not get the error