Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call API in c# using angularjs

Hi I am calling my API using below code

  $http.get('/api/controller/method?param=value').
           then(function (response) {
               if (response.status == 200) {
                   console.log(response.data);
               }
           });

It is working fine in my local machine (http://localhost/api/controller/method?param=value).

But when I deployed it in server with application name app, it is not able to call the API(http://server-ip/app/api/controller/method?param=value).

Obviously, it won't, as URL are different. So what is the correct way to call an API in c# so that it will work in any server.

What I have tried:
1. URL.Action : It is not working in this case.
2. I don't want to Use @HTML.hidden
3. Call starting with or without slash (/)

like image 709
user3035305 Avatar asked Dec 14 '15 08:12

user3035305


People also ask

Can you make API calls in C?

Applications call C API functions defined in C language header files, and a dynamic link library (DLL). Each function call returns an integer result code, defined in the ctgstdat. h header file. A function that completes normally returns the code CTG_STAT_OK .

Can C handle API requests?

Of course! Calling an API is just a matter of making HTTP requests to a server you can do it from pretty much any language. C has a number of excellent network socket libraries to use.

What is REST API in C?

A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.


1 Answers

I usually solve this by using a factory like this -

First in the .cshtml page I load all the angular js required. Then create a factory for the baseURL like this -

function(angular){
    var module = angular.module('NameOfMyModule');  //gt the module
    module.factory('BaseUrl', function(){
         return '@Url.Action("Action", "Controller")';
    });
}(window.angular);

Then inject that BaseURL inside the controller -

....
module.controller('SomeController', [...., 'BaseUrl', function(...., BaseUrl){
     $scope.baseUrl = BaseUrl;

}]);

....`

Finally prepend it in the url

$http.get($scope.baseUrl + /...../).then(....);
like image 177
brainless coder Avatar answered Nov 03 '22 23:11

brainless coder