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;
}
Related
I am a begginer and i work in a MVC project which I cant understand it well yet.
I can't understand where does the API takes data from when I try to connect in Login Screen.
It doesn't use Entity Framework and there isn't a json with the data.
When I enter Id and Pass it calls an API (GetAPIResponse) which somehow finds that is correct.
Need help to understand the code and the logic behind it.
LoginBL class contains:
public bool IsAuthenticated(LoginEntity user)
{
string url = string.Empty;
string callType = string.Empty;
string server = string.Empty;
try
{
// get URL, Call type, Server from config file
url = ConfigurationManager.AppSettings["login_url"].ToString();
callType = ConfigurationManager.AppSettings["calltype"].ToString();
server = ConfigurationManager.AppSettings["server"].ToString();
// Encrypt password
string password = Scrambler.GenerateMD5Hash(user.Password);
// Prepare content for the POST request
string content = #"calltype=" + callType + "&server=" + server + "&user=" + user.UserName + "&pass=" + password + "";
Debug.WriteLine("Callcenter login url: " + content);
HttpResponseMessage json_list = ApiCallBL.GetAPIResponse(url, content);
LoginResponseEntity obj = new LoginResponseEntity();
obj = JsonConvert.DeserializeObject<LoginResponseEntity>(json_list.Content.ReadAsStringAsync().Result);
Debug.WriteLine(callType + " Response: " + json_list.Content.ReadAsStringAsync().Result);
//if API resultCode return 0 then user details and token save in session for further use
if (obj.ResultCode == 0)
{
int restrict = obj.UserInfo.RestrictCallType.HasValue ?
obj.UserInfo.RestrictCallType.Value : 0;
HttpContext.Current.Session["user_id"] = obj.UserInfo.usr_id;
HttpContext.Current.Session["user_name"] = obj.UserInfo.usr_username;
HttpContext.Current.Session["user_group_id"] = obj.UserInfo.UserGroupID;
HttpContext.Current.Session["groupid"] = obj.UserInfo.groupid;
HttpContext.Current.Session["token"] = obj.Token;
HttpContext.Current.Session["web_server_url"] = obj.ServerInfo.web_server_url;
HttpContext.Current.Session["centerX"] = obj.ServerInfo.DefaultGeoX;
HttpContext.Current.Session["centerY"] = obj.ServerInfo.DefaultGeoY;
HttpContext.Current.Session["dateFormat"] = obj.ServerInfo.dateFormat;
HttpContext.Current.Session["currency"] = obj.ServerInfo.currency;
HttpContext.Current.Session["customer_img"] = obj.ServerInfo.customer_img;
HttpContext.Current.Session["groups"] = obj.groups;
HttpContext.Current.Session["restrict_call_type"] = restrict ;
Debug.WriteLine("obj.UserInfo.UserGroupID " + obj.UserInfo.UserGroupID);
Debug.WriteLine("obj.UserInfo.groups " + obj.groups);
//HttpContext.Current.Session["defaultLanguage"] = obj.ServerInfo.defaultLanguage;
HttpCookie cookie = new HttpCookie("Login");
// if remember me checked then user name and password stored in cookie else cookes is expired
if (user.RememberMe)
{
cookie.Values.Add("user_name", obj.UserInfo.usr_username);
cookie.Values.Add("pwd", user.Password);
cookie.Expires = DateTime.Now.AddDays(15);
HttpContext.Current.Response.Cookies.Add(cookie);
}
else
{
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(cookie);
}
return true;
}
else
{
//ResultCode -5 :Invalid Login ,-1:Database Error ,-2:Server Error ,-3:Invalid Parameter specified ,-4:Invalid Token
return false;
}
}
catch
{
throw;
}
finally
{
url = string.Empty;
callType = string.Empty;
server = string.Empty;
}
}
Okay here after converts pass to MD5 creates a "string content" with the information given.
Then in next line (HttpResponseMessage json_list = ApiCallBL.GetAPIResponse(url, content);) calls the API with the url and content as parameters where it finds if the data exists.
API code:
public static HttpResponseMessage GetAPIResponse(string url, string content)
{
StringBuilder traceLog = null;
HttpContent httpContent = null;
try
{
traceLog = new StringBuilder();
traceLog.AppendLine("Start: BusinessLayer getAPIResponse() Request Data:- " + DateTime.Now + "URL = " + url + "&content = " + httpContent);
using (HttpClient client = new HttpClient())
{
httpContent = new StringContent(content);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var resp = client.PostAsync(url, httpContent).Result;
Debug.WriteLine("resp: " + resp.Content.ReadAsStringAsync().Result);
traceLog.AppendLine("End: BusinessLayer getAPIResponse() call completed HttpResponseMessage received");
return resp;
}
}
catch
{
throw;
}
finally
{
traceLog = null;
httpContent.Dispose();
url = string.Empty;
content = string.Empty;
}
}
In the following line, console prints the result that I cant understand where it cames from (Debug.WriteLine("resp: " + resp.Content.ReadAsStringAsync().Result);)
Sorry for the confusion , I am in my first job with zero work experience and I am called to learn how this works alone without proper education on ASP.NET from them.
You will not go very far without debbugger. Learn how to debug in Visual Studio (YouTube tutorials might be fastest way). Place debug points along critical points in code (for example moment when client sends and receives response is line var resp = client.PostAsync...) and check variables.
Url for API server is actually defined in the line
url = ConfigurationManager.AppSettings["login_url"].ToString();
ConfigurationManager means Web.config file, check it's appSettings section for login_url entry, there is your url.
Btw, using (HttpClient client = new HttpClient()) is not a good way to use a HttpClient and will lead to port exhaustion. It's ok for small number of requests, but for larger ones you must reuse it, or use HttpClientFactory (for .NET Core).
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)
}
});
...
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();
}
How to send parameter in REST api in xamarin.forms ?
I have created REST API Project in xamarin using PCL.
When I call Simple REST api using Below code in Xamarin.forms (Portable Class Library) then I have Successfully receive json Response.
using (var cl = new HttpClient())
{
var result = await cl.GetStringAsync("http://192.168.1.100/apps/jara/web/api/user/test");
jsonResponseClass des = JsonConvert.DeserializeObject<jsonResponseClass>(result);
lbl1.Text = des.code + " " + des.status + " " + des.message;
}
public class jsonResponseClass
{
public string code { get; set; }
public string status { get; set; }
public string message { get; set; }
}
Using above code I got a response
{
code: 200,
status: "ok",
message: "hello"
}
REST API response type is JSON and type is POST
Now, I want to call below Login Api using paramater.
http://192.168.1.100/apps/jara/web/api/user/login
Paramater : email_id and Password
this api success response type is....
{
code: 200,
status: "Success",
User: {
userid: 126,
token: "d154s4d54s654df5s4df56s4df564s5df4",
email: "shahbuddin#gmail.com",
mobile_number: "9898989898"
},
message: "Successfully logged in"
}
What can i do ?
Finally i can do this using below code....
using (var cl = new HttpClient())
{
var formcontent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("email_id","shahbuddin#peerbits.com"),
new KeyValuePair<string, string>("password","shah")
});
var request = await cl.PostAsync("http://192.168.1.100/apps/jara/web/api/user/login", formcontent);
request.EnsureSuccessStatusCode();
var response = await request.Content.ReadAsStringAsync();
jsonResponselogin res = JsonConvert.DeserializeObject<jsonResponselogin>(response);
lbl1.Text = res.code + " " + res.status + " " + res.message;
}
This code helpful for Calling REST API with Parameter
Thank you...
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.