call the Web api get method using data params c# - c#

I am able to call the Web api method in client side and now i want make it in c# code. Here i am writing my jquery code.
$(document).ready(function ()
{
$('#btnSubmit').click(function ()
{
var Params =
{
AsOndate: Todate,
BCRefCode: 100,
AccID: 90000
};
$.ajax({
type: "GET",
url: 'http://localhost:51093/api/account/',
//url: 'http://192.168.0.171:51093/api/account/',
data: Params,
dataType: "json",
traditional: true,
success: ajaxSuccess,
error: ajaxError
});
});
and i am calling the web api method
public IEnumerable GetAccountListForMapping(Params param)
{
AccList _AccList = new AccList();
ListParams lstParam = new ListParams();
//lstParam.Add("#FromDate", Fromdate);
lstParam.Add("#AsOnDate", param.AsOndate);
lstParam.Add("#BCRefCode", param.BCRefCode);
lstParam.Add("#AccID", param.AccID);
_AccList = (AccrList)_AccList.GetAccountMappedList(lstParam);
return _AccList;
}
This is working good in jquery call.. And how to write the same C# code
This is what i tried
Params param1 = new Params();
param1.AsOndate = System.DateTime.Today;
param1.AccID = 90000;
param1.BCRefCode = 100;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:51093/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("/api/account", param1, new JsonMediaTypeFormatter()).Result;
if (response.IsSuccessStatusCode)
{.....
}

Got the answer and it worked for me
protected void btnGetdata_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:xxxx/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string param = "AsOnDate=" + System.DateTime.Today + "&AccID=" + 90000 + "&BCRefCode=" + 100;
HttpResponseMessage response = client.GetAsync("/api/account?" + param, HttpCompletionOption.ResponseContentRead).Result;
if (response.IsSuccessStatusCode)
{
var aa = response.Content.ReadAsAsync<object>().Result;
object obj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<YourClassName>>(aa.ToString());
}
}
Thanks to all

Use this method.
string param = "AsOndate=" + System.DateTime.Today + "&AccID=" + 90000 + "&BCRefCode=" + 100;
HttpResponseMessage response = client.GetAsync("/api/account?" + param,HttpCompletionOption.ResponseContentRead).Result;
Thanks.

continuing with the answer given by #felix
It will surely get the error as you have not changed the parameter for the api code :
public IEnumerable GetAccountListForMapping(string param)
{
// Your Code
}
and now extract that data from the 'param' string.
I hope this will work.

Related

VOID code behind working. String return using Ajax not working. (Checking PayPal details)

I'm trying to convert a void code behind call to PayPal which checks a users PayPal details, to an Ajax call to work in the background.
I'm struggling to
Turn from Void to a String to return the value for Ajax
When I do use my method of a string, it just times out - even if I set timeout to a ridiculously high number. Then it fails and just comes back as undefined.
Working code behind void code:
public async void checkAccAsync()
{
userManager um = new userManager();
var userID = HttpContext.Current.User.Identity.GetUserId();
um.Get(userID);
var subid = um.ppID.Trim();
var token = getToken();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.paypal.com/v1/billing/subscriptions/" + subid))
{
var id = "";
var nextPayment = "";
var status = "";
var payerEmail = "";
var currency = "";
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
var response = await httpClient.SendAsync(request);
string res = await response.Content.ReadAsStringAsync();
var obj2 = JsonConvert.DeserializeObject<dynamic>(res);
id = obj2.id;
nextPayment = obj2.billing_info.next_billing_time;
if (nextPayment == null)
{
nextPayment = obj2.billing_info.last_payment.time;
var nextPayment2 = Convert.ToDateTime(nextPayment);
nextPayment2.AddMonths(1);
nextPayment = nextPayment2.ToString();
}
status = obj2.status;
status = status.ToLower();
status = FirstLetterToUpper(status);
payerEmail = obj2.subscriber.email_address;
currency = obj2.shipping_amount.currency_code;
um.updatePaypal_noIPN(id, status, "Regular", nextPayment, payerEmail, currency);
}
}
}
Ajax call with String (ideal method), which isn't working.
[WebMethod]
public async System.Threading.Tasks.Task<string> CheckAccAsync()
{
userManager um = new userManager();
var userID = HttpContext.Current.User.Identity.GetUserId();
um.Get(userID);
var subid = um.ppID.Trim();
var token = getToken();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.paypal.com/v1/billing/subscriptions/" + subid))
{
var id = "";
var nextPayment = "";
var status = "";
var payerEmail = "";
var currency = "";
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
var response = await httpClient.SendAsync(request);
string res = await response.Content.ReadAsStringAsync();
var obj2 = JsonConvert.DeserializeObject<dynamic>(res);
id = obj2.id;
nextPayment = obj2.billing_info.next_billing_time;
if (nextPayment == null)
{
nextPayment = obj2.billing_info.last_payment.time;
var nextPayment2 = Convert.ToDateTime(nextPayment);
nextPayment2.AddMonths(1);
nextPayment = nextPayment2.ToString();
}
status = obj2.status;
status = status.ToLower();
status = FirstLetterToUpper(status);
payerEmail = obj2.subscriber.email_address;
currency = obj2.shipping_amount.currency_code;
um.updatePaypal_noIPN(id, status, "Regular", nextPayment, payerEmail, currency);
return status + ", "+payerEmail+", ";
}
}
}
And the jQuery which calls it:
$( document ).ready(function() {
$.ajax({
type: "POST",
url: '/WebServices/checkPayPal.asmx/CheckAccAsync',
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError,
timeout: 150000
});
});
function OnSuccess(data, status) {
alert(data.d);
}
function OnError(data, status) { // error 2
alert(data.error)
};
Why isn't my Ajax string method not working?

Error in $Ajax ASP.NET web method call [async]

I am working over async web method (asmx file) and I need to call this method throughout an ajax jquery method however I am facing a lot of issues because the method uses also Entity Framework to run some other things.
Here is JavaScript:
function SubmitStripeForm() {
// event.preventDefault();
stripe.createToken(card).then(function (result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
// stripeTokenHandler(result.token);
console.log();
var myToken = result.token.id;
$.ajax({
type: "POST",
url: "http://localhost:54355/Account/API/Stripe.asmx/MyStripePayment",
crossDomain: true,
async: false,
data: '{Tok: "' + myToken + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d) {
console.log("Good");
}
else {
console.log("Bad");
}
},
failure: function (response) {
console.log("HORRIBLE");
}
});
}
});
Here is the web method in asp.net c#:
[WebMethod(EnableSession = true)]
public async void MyStripePayment(string Tok)
{
string MyToken = Tok;
using (var context = new CompanyEntities())
{
var collection = (from p in context.COMPANY where p.Id == Company_Id select p);
foreach (var item in collection)
{
// Validation of the object
BillingManagement.Michael Maik = new BillingManagement.Michael();
Maik.name = "Michael";
Maik.id = "114060502";
Maik.number = "83290910";
#region Send Information To Stripe
CancellationToken Token = new CancellationToken();
string Url = "http://localhost:5000/testing/give-your-data";
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
{
var json = JsonConvert.SerializeObject(Maik);
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
request.Content = stringContent;
using (var response = await client
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Token)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
string resString = await response.Content.ReadAsStringAsync();
JObject jObject = JObject.Parse(resString);
string message = (string)jObject["message"];
}
}
}
#endregion
}
}
and this is the error displayed:
POST http://localhost:54355/Account/API/Stripe.asmx/MyStripePayment 500 (Internal Server Error)
have you tried using Try/Catch to get more information about the error? obviously it is something internal, better used it like that and try again to see what error it is.
try
{
// Code
}
catch (Exception ex)
{
console.writeLine(ex);
}
OR
You put an intervention in the catch to be able to see in local variables the values ​​of the "Ex" or save the error somewhere to read it later.

send value from Angular service App to C# backend controller

I'm getting absolutely insane with this, I've tried almost everything and can't find a way to pass a string value from a service to backend to return Json result based on that string.
Here's the problem, I have a backend that cooks all the JSON with meta-info that
frontend provides, and then return them to the frontend to display, on this case I have to get a JSON that's based on a filter that is made by a string inserted in frontend but can't find a way to pass the string to the backend, and I don't want to pass it through the URL.
Here's my code:
angular typescript service: I want to pass the "whr"
getAdvancedFilterResult(concept: string, whr: string): Promise<any> {
const headers: Headers = new Headers({
'Content-Type': 'application/json'
});
this.authService.getAuthorizationHeader(headers);
headers.append('IdLng', this.config.idLanguage);
const options: RequestOptions = new RequestOptions();
options.headers = headers;
return this.http.get(this.config.apiDomain + this.config.apiEndpointEntities + '/' + concept + '/' + "filtered",
options
)
.toPromise()
.then(
response => response.json() as any[]
)
.catch((error) => this.customHandleError(error, this.toastrService));
}
Backend controller:
[Route("api/Entities/{entity}/filtered/")]
public HttpResponseMessage GetFilter(string entity) {
HttpResponseMessage response = new HttpResponseMessage();
string action = "READ";
//Check Authorization
AuthorizationResponse authResponse = AuthProvider.CheckAuthorization(new AuthorizationRequest() {
SCode = UserUtils.GetUserSCode(User),
ConceptString = entity,
ActionString = action,
UserId = UserUtils.GetUserID(User),
ExtraParameters = new AuthorizationRequest.ExtraParamaters() {
IdsOnly = false, Where = "!!!!!WHR HERE!!!!"
}
});
if (authResponse.IsAuthorized) {
//code
response = Request.CreateResponse(HttpStatusCode.OK, json);
} else {
response = Request.CreateResponse(HttpStatusCode.Unauthorized);
}
return response;
}
Should I pass it through the header, with headers.append('whr', whr);, that goes into the options on http.get or into body with options.body = whr;?
Also, how can I get it on the backend side to use?
You should pass the Headers like this:
getAdvancedFilterResult(concept: string, whr: string): Promise<any> {
this.authService.getAuthorizationHeader(headers);
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('x-corralation-id', '12345');
headers = headers.append('IdLng', this.config.idLanguage);
headers = headers.append('whr', whr);
const options: RequestOptions = new RequestOptions();
options.headers = headers;
return this.http.get(this.config.apiDomain + this.config.apiEndpointEntities + '/' + concept + '/' + "filtered",
options
)
.toPromise()
.then(
response => response.json() as any[]
)
.catch((error) => this.customHandleError(error, this.toastrService));
}
To get the headers on the Server Side try this:
[Route("api/Entities/{entity}/filtered/")]
public HttpResponseMessage GetFilter(string entity) {
var request = Request;
var headers = response.Headers;
HttpResponseMessage response = new HttpResponseMessage();
string action = "READ";
var whrHeader = headers.Contains("whr") ? request.Headers.GetValues("whr").First() : ""
AuthorizationResponse authResponse = AuthProvider.CheckAuthorization(new AuthorizationRequest() {
SCode = UserUtils.GetUserSCode(User),
ConceptString = entity,
ActionString = action,
UserId = UserUtils.GetUserID(User),
ExtraParameters = new AuthorizationRequest.ExtraParamaters() {
IdsOnly = false,
Where = whrHeader
}
});
if (authResponse.IsAuthorized) {
//code
response = Request.CreateResponse(HttpStatusCode.OK, json);
} else {
response = Request.CreateResponse(HttpStatusCode.Unauthorized);
}
return response;
}
I got the solution, thanks to SiddAjmera!!
At frontend service:
getAdvancedFilterResult(concept: string, whr: string): Promise<any> {
let headers: Headers = new Headers();
this.authService.getAuthorizationHeader(headers);
headers.append('Content-Type', 'application/json');
headers.append('IdLng', this.config.idLanguage);
headers.append('whr', whr);
const options: RequestOptions = new RequestOptions();
options.headers = headers;
return this.http.get(
this.config.apiDomain + this.config.apiEndpointEntities + '/' + concept + '/' + "filtered",
options
)
.toPromise()
.then(
response => response.json() as any[]
)
.catch((error) => this.customHandleError(error, this.toastrService));
}
And then on the backend, just used the UserUtils already made to get the header which has the value 'whr' and pass it through a function.
UserUtilis.cs:
public static string Where(HttpRequestMessage re) {
string whereCLause = "";
var headers = re.Headers;
if (headers.Contains("whr")) {
whereCLause = headers.GetValues("whr").First();
} else {
whereCLause = " ";
}
return whereCLause;
}
And Controller.cs
...
var re = Request;
HttpResponseMessage response = new HttpResponseMessage();
string action = "READ";
//Check Authorization
AuthorizationResponse authResponse = AuthProvider.CheckAuthorization(new AuthorizationRequest() {
SCode = UserUtils.GetUserSCode(User),
ConceptString = entity,
ActionString = action,
UserId = UserUtils.GetUserID(User),
ExtraParameters = new AuthorizationRequest.ExtraParamaters() {
IdsOnly = false, Where = UserUtils.Where(re)
}
});
...

Instagram Api (https://api.instagram.com/oauth/access_token" , "post" , parameters) returns 400 Bad Request

I am developing an app using instagram api to bring feed to my website. I have following code but when i try to access the access_token using the code provided by Instagram it's giving me `400 Bad request error. I would be much obliged if someone could help me to overcome this problem. Many Thanks
string code="";
public ActionResult Index()
{
if (!String.IsNullOrEmpty(Request["code"]))
{
code = Request["code"].ToString();
GetDataInstagramToken();
}
return View();
}
public ActionResult Instagram()
{
var client_id = ConfigurationManager.AppSettings["instagram.clientid"].ToString();
var redirect_uri = ConfigurationManager.AppSettings["instagram.redirecturi"].ToString();
string url = "https://api.instagram.com/oauth/authorize/?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=code";
Response.Redirect(url);
return View();
}
public void GetDataInstagramToken()
{
var json = "";
var page = HttpContext.CurrentHandler as Page;
try
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", ConfigurationManager.AppSettings["instagram.clientid"].ToString());
parameters.Add("client_secret", ConfigurationManager.AppSettings["instagram.clientsecret"].ToString());
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", ConfigurationManager.AppSettings["instagram.redirecturi"].ToString());
parameters.Add("code", code);
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
var response = System.Text.Encoding.Default.GetString(result);
// deserializing nested JSON string to object
var jsResult = (JObject)JsonConvert.DeserializeObject(response);
string accessToken = (string)jsResult["access_token"];
int id = (int)jsResult["user"]["id"];
//This code register id and access token to get on client side
page.ClientScript.RegisterStartupScript(this.GetType(), "GetToken", "<script> var instagramaccessid=\"" + #"" + id + "" + "\"; var instagramaccesstoken=\"" + #"" + accessToken + "" + "\";</script>");
}
catch (Exception ex)
{
throw;
}
}
I am getting exception at
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
In this line
client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
You don't send any value to Instagram. If you check your parameter you can see your key but you cant see any value.
Try this:
public async void GetTokenFromCode()
{
var values = new Dictionary<string, string> {
{ "client_id","Your ChatId" },
{ "client_secret", "Your Client Secret" },
{ "grant_type", "authorization_code" },
{ "redirect_uri", "Your Redirect url"},
{ "code", "code" } };
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://api.instagram.com/oauth/access_token", content);
var responseString = await response.Content.ReadAsStringAsync();
}

Asp.net WebApi method instead of AngularJs Service

I have written Angularjs service as shown below.It retrieves data from the 3rd party service.It's working fine.
Now I have a requirement to write a WebApi method for the same.The reason for that is, we can consume that service from various types of applications.i.e. desktop, web and mobile.How can I implement such a service?
AngulaJS service:
(function () {
appModule.service('getPropertyDetailsByUsingApiService', ['$http', function ($http) {
this.propertyDetails = function (token, number, street, county, zip) {
var endpointUrl = 'http://myaddress.com/api/AddressMatcher?Token=';
var url = endpointUrl + token + '&Number=' + number + '&Street=' + street + '&County=' + county + '&Zip=' + zip;
return $http.get(url).then(function (data) {
var result = data;
if (result.data[0].Status == 'OK') {
return $http.get(endpointUrl + token + '&Apn=' + result.data[0].Result[0].APN + '&County=' + county)
.then(function (finalData) {
return finalData;
});
} else {
return null;
}
});
};
}
]);
})();
WebApi method :
[HttpGet]
public async Task<MyModelDto> GetPropertyDetailsByUsingApiService()
{
//I would like to have a help here to implement it
return result;
}
I guess you are looking for HttpClient.GetAsync.
For example,
var response = await client.GetAsync("http://...");
if (response.IsSuccessStatusCode) {
...
}
Use this,
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiDetails.BaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync(apiDetails.RequestUrl, obj).Result;
}

Categories