RESTSHARP errors ( IRestResponse, Method.GET, Execute) - asp.net-core

public virtual string GetPaymentStatus(HttpContext context, NGeniusConfiguration configuration)
{
var reference = context.Request.Query[NGeniusConstants.ApiQueryStringRef].ToString();
var token = GetAccessToken(configuration);
var url = new Uri(GetPaymentBaseUrl(configuration), string.Format(NGeniusConstants.ApiUrl.OrderStatus, configuration.OutletId, reference));
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", string.Format(NGeniusConstants.ApiauthorizationMode.Bearer, token));
request.AddHeader("accept", NGeniusConstants.ApiPaymentAcceptJson);
IRestResponse response =client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
var status = JsonConvert.DeserializeObject<NGeniusOrderStatusResponse>(response.Content);
return status.Embedded.Payment.First().State;
}
else
{
throw new Exception("Error while getting the order status", response.ErrorException);
}
}
I am fairly new to .Net Core. Can someone tell me why I have errors in Method.GET, IRestResponse and Execute? I have already included "using RestSharp;" in the program as well.
for more reference the the project i am implementing is from GITHUB.

Related

Asp.Net Core - Making API calls from backend

I have an application which is calling API's from a backend cs class, using IHostedService. With basic API calls ("http://httpbin.org/ip") it is working fine and returning the correct value, however I now need to call a Siemens API which requires me to set an Authorization header, and place "grant_type=client_credentials" in the body.
public async Task<string> GetResult()
{
string data = "";
string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
using (HttpContent content = res.Content)
{
data = await content.ReadAsStringAsync();
}
}
}
I think I have the header set up correctly but I won't know for sure until the full request gets formatted. Is it even possible to set the the body of the request to "grant_type=client_credentials"?
As far as I can see from Siemens API documentation they expect Form data, so it should be like:
public async Task<string> GetResult()
{
string data = "";
string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
});
using (HttpResponseMessage res = await client.PostAsync(baseUrl, formContent))
{
using (HttpContent content = res.Content)
{
data = await content.ReadAsStringAsync();
}
}
}
}

register user to .net core from mobile

i try to register user from xamarin in .net core with enabled Identity and membership system it return true but no user registered in database.
also i check with MVC web site and all things is Ok
my code is
using (var client = new HttpClient())
{
var model = new RegisterBindingModel
{
Email = email,
Password = password,
ConfirmPassword = confirmPassword
};
var json = JsonConvert.SerializeObject(model);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(
Constants.SignalrEndpointAddress + "Account/Register", httpContent);
if (response.IsSuccessStatusCode)
{
return true;
}
}
problem is in StringContent and my code ended up to this:
using (var client = new HttpClient())
{
var model = new Dictionary<string, string>
{
{"Email", email },
{"Password", password},
{"ConfirmPassword", confirmPassword},
};
var httpContent = new FormUrlEncodedContent(model);
var response = await client.PostAsync(
Constants.EndpointAddress + "Account/Register", httpContent);
if (response.IsSuccessStatusCode)
{
return true;
}
}
thanks

PostAsync request with Array parameter on MVC Web API

I have Xamarin application that has POST request with array list of parameter and on my MVC WEB API we used code first Entity framework. Both was separated project solutions (.sln).
On my Xamarin project, I have PostAsync request which supplies List of array values.
using (var client = new HttpClient())
{
Parameter = string.Format("type={0}&param={1}",type, param[]);
var data = JsonConvert.SerializeObject(parameters);
var content = new StringContent(data, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync(url, content))
{
using (var responseContent = response.Content)
{
result = await responseContent.ReadAsStringAsync();
}
}
}
Then In my Web API controller I have same parameter with my client side also.
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpPost]
[Route("type={type}&param={param}")]
public BasicResponse applog([FromUri] ProfilingType type , List<string> param)
{
if (ModelState.IsValid == false)
{
throw new ModelValidationException("Model state is invalid.");
}
try
{
if(type == ProfilingType.Login)
{
var command = new SendDataProfilingCommand(param);
CommandHandler.Execute(command);
}
else
{
var command = new UpdateDataProfilingCommand(type,param);
CommandHandler.Execute(command);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return new BasicResponse
{
Status = true,
Message = Ok().ToString()
};
}
Since I'm not with the API, I want to test it first on Postman or even in the URL. but my problem was when i Try to test it using this url below
http://localhost:59828/api/users/applog?type=1&param=[1,Caloocan,Metro Manila,Philippines,0,0]
I received this message : No HTTP resource was found that matches the request URI ......
My Question is, How can I test my Web API with List Parameter on URL or in the Postman ? and What Format I can use when sending a post request into my Xamarin PostAsync request?
You don't need to send as Content.
using (var client = new HttpClient())
{
Parameter = string.Format("type={0}&param={1}",type, param[]);
url = url + "?" + Parameter;
using (var response = await client.PostAsync(url))
{
using (var responseContent = response.Content)
{
result = await responseContent.ReadAsStringAsync();
}
}
}

how to make a request to my .NET Core App from UWP, with Microsoft Account Authentication

Update
some code on web side
startup.cs
app.UseOAuthAuthentication(new OAuthOptions()
{
AuthenticationScheme = "Microsoft-AccessToken",
DisplayName = "MicrosoftAccount-AccessToken",
ClientId = {CliendID},
ClientSecret = {ClientSecret},
CallbackPath = new PathString("/signin-microsoft-token"),
AuthorizationEndpoint = MicrosoftAccountDefaults.AuthorizationEndpoint,
TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint,
UserInformationEndpoint = MicrosoftAccountDefaults.UserInformationEndpoint,
Scope = { "https://graph.microsoft.com/user.read" },
SaveTokens = true,
Events = new OAuthEvents()
{
OnCreatingTicket = async context =>
{
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var user = JObject.Parse(await response.Content.ReadAsStringAsync());
var identifier = user.Value<string>("id");
if (!string.IsNullOrEmpty(identifier))
{
context.Identity.AddClaim(new Claim(
ClaimTypes.NameIdentifier, identifier,
ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
var userName = user.Value<string>("displayName");
if (!string.IsNullOrEmpty(userName))
{
context.Identity.AddClaim(new Claim(
ClaimTypes.Name, userName,
ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
var email = user.Value<string>("userPrincipalName");
if (!string.IsNullOrEmpty(email))
{
context.Identity.AddClaim(new Claim(
ClaimTypes.Email, email,
ClaimValueTypes.Email, context.Options.ClaimsIssuer));
}
}
}
});
HomeController.cs
[Authorize]
public string GetInfo()
{
return "Hello world!";
}
I am able to retrieve user's token with code like this
string MicrosoftClientID = {ClientID};
string MicrosoftCallbackURL = "urn:ietf:wg:oauth:2.0:oob";
string scope = WebUtility.UrlEncode("openid offline_access https://graph.microsoft.com/user.read");
string MicrosoftURL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id=" + MicrosoftClientID + "&response_type=code&redirect_uri=" + MicrosoftCallbackURL + "&response_mode=query&scope=" + scope;
Uri StartUri = new Uri(MicrosoftURL);
Uri EndUri = new Uri(MicrosoftCallbackURL);
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
StartUri,
EndUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
string code = WebAuthenticationResult.ResponseData.Replace("urn:ietf:wg:oauth:2.0:oob?code=", "");
string strContent = "client_id=" + MicrosoftClientID + "&scope=" + scope + "&code=" + code + "&redirect_uri=" + MicrosoftCallbackURL + "&grant_type=authorization_code";
HttpClient httpClient = new HttpClient();
HttpContent httpContent = new StringContent(strContent);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("https://login.microsoftonline.com/consumers/oauth2/v2.0/token", httpContent);
string stringResponse = await httpResponseMessage.Content.ReadAsStringAsync();
}
but how can i use the token to make a request to API of my .NET Core Web application, which is hosted on azure?
I have tried these
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationModel.AccessToken);
string apicontent = await httpClient.GetStringAsync("https://{host}.azurewebsites.net/home/GetInfo");
apicontent.ToString();
all I got is html of login page
Any help please?
This Authorize is as same as an normal web application.
If you don't want to authenticate the user when you call this API, you can remove the attribure [Authorize] for the GetInfo. And if you also have [Authorize] attribure for the controller, you can add [AllowAnonymous] attribute to specify this action is skipped by AuthorizeAttribute during authorization.
You can refer to here about Authentication and Authorization.
Let's start from the Web Api:
Here is my sample method to retrieve friends list from the Api.
Note that there is "Route prefix" attribute - to indicate which resource I would like to retrieve and "Authorize" attribute to demand authentication before calling this method:
[RoutePrefix("api/Friends")]
public class FriendsController : ApiController
{
[Authorize]
[Route("GetConfirmedFriends")]
public IHttpActionResult GetConfirmedFriends()
{
using (DbWrapper dbContext = new DbWrapper())
{
return Ok(dbContext.GetConfirmedFriends());
}
}
}
Now in the UWP application you will call this method like below:
public async Task<ObservableCollection<Friend>> GetConfirmedFriends()
{
//access token eretrieved after MS authentication:
if (_accessToken == null)
throw new NullReferenceException("Access token cannot be empty. Please authenticate first");
try
{
using (HttpClient client = new HttpClient())
{
ObservableCollection<Friend> friends = null;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _accessToken);
var data = await client.GetAsync(string.Concat(https://{host}.azurewebsites.net/, "api/Friends/GetConfirmedFriends"));
var jsonResponse = await data.Content.ReadAsStringAsync();
if (jsonResponse != null)
friends = JsonConvert.DeserializeObject<ObservableCollection<Friend>>(jsonResponse);
return friends;
}
}
catch (WebException exception)
{
throw new WebException("An error has occurred while calling GetConfirmedFriends method: " + exception.Message);
}
}
Please check and let me know.

How to receive a response package from GET request for OneNote API

I'm getting a acknowledgement but no response message (details) i.e. list of notebooks from the OneNote API. Below is my code. I am able to receive the header and JSON details from a POST message but not the GET. I have tried to convert the POST code in order to submit a GET request.
private async void getRequestClick(object sender, RoutedEventArgs e)
{
await GetRequests(true, "test");
}
async public Task<StandardResponse> GetRequests(bool debug, string sectionName)
{
Uri PagesEndPoint1 = new Uri("https://www.onenote.com/api/v1.0/notebooks");
var client = new HttpClient();
//// Note: API only supports JSON return type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//// This allows you to see what happens when an unauthenticated call is made.
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authClient.Session.AccessToken);
}
HttpResponseMessage response;
HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Get, PagesEndPoint1);
response = await client.SendAsync(createMessage);
tbResponse.Text = response.ToString();
return await TranslateResponse(response);
}
private async static Task<StandardResponse> TranslateResponse(HttpResponseMessage response)
{
StandardResponse standardResponse;
if (response.StatusCode == HttpStatusCode.Created)
{
dynamic responseObject = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
standardResponse = new CreateSuccessResponse
{
StatusCode = response.StatusCode,
OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
};
}
else
{
standardResponse = new StandardErrorResponse
{
StatusCode = response.StatusCode,
Message = await response.Content.ReadAsStringAsync()
};
}
// Extract the correlation id. Apps should log this if they want to collcet the data to diagnose failures with Microsoft support
IEnumerable<string> correlationValues;
if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues))
{
standardResponse.CorrelationId = correlationValues.FirstOrDefault();
}
return standardResponse;
}
My POST messages are working OK. I can create a new page etc.
I think you need to change the expected status code from HttpStatusCode.Created to HttpStatusCode.OK for Get requests, since they return a 200 and not a 201. Try doing that in your TranslateResponse method.