Angular : Error calling WCF service using AngularJS $http - angularjs

Error while trying to access WCF service using AngularJS $http. Here is the AngularJS code :
$http({
method: 'POST',
url: 'http://localhost:59412/ToDoService.svc/SignIn',
params: JSON.stringify({ username: 'jay' }),
headers: {
"Content-Type": "application/json"
}
})
.then(function (res) {
console.log(res);
})
Here is the WCF web service code (ToDoService.svc.cs) :
public void SignIn(string username)
{
}
ToDoService.svc code is :
[ServiceContract]
public interface IToDoService
{
[OperationContract]
[WebInvoke(Method = "POST")]
void SignIn(string username);
}
The error shown in browser console is :
POST http://localhost:59412/ToDoService.svc/SignIn?0=%7B&1=%22&10=%22&11=:&12=%22&13=j&14=a&15=y&16=%22&17=%7D&2=u&3=s&4=e&5=r&6=n&7=a&8=m&9=e 500 (Internal Server Error)
NOTE: Works fine if I remove the params from the service call.

replace params with data option
data: JSON.stringify({ username: 'jay' })

Related

Post null value from ionic to asp.net web Api

I tried to make a post request from ionic to web api this way
ionic code
$http({
url: 'http://localhost:1449/api/IonicApi',
method: "POST",
data: {
firstName : "a",
lastName : "b",
email : "ab#ab.com"
},
headers: { 'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8" }
}).then(function (response) {
// success
$ionicPopup.alert({
title: 'Your Name is '+$scope.man.firstName + ' '+$scope.man.lastName,
template: 'It might taste good'
})
}, function (response) { // optional
// failed
console.log('failed');
});
and the c# part is
public IHttpActionResult Post(tblPerson person)
{
db = new MobileDBEntities();
db.tblPersons.Add(person);
db.SaveChanges();
return Ok();
I tried from postman to post data it was working. But from Ionic it is passing null data of object
What wrong did I make here?
Postman screenshot I am adding here
Is it possible to call you api like below where obj is your data
$http.post('http://localhost:1449/api/IonicApi',obj).success(function(){
}).error(function()
{
});

angular $http post not sending data for service

I´m trying user $http post in angular, where the rest service receive an object. The data is a Json where I need pass with parameter for method in service.
My angular code (it´s doesn´t work for me):
$http({
method:'POST',
url:request.url,
data: JSON.stringify(objcsr);
headers: {'Content-Type':'application/json; charset=utf-8'}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
debugger;
alert('error:- '+JSON.stringify(objE));
});
If I comment the row data, the comunication with service it´s ok:
$http({
method:'POST',
url:request.url,
//data: JSON.stringify(objcsr);
headers: {'Content-Type':'application/json; charset=utf-8'}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
debugger;
alert('error:- '+JSON.stringify(objE));
});
My method in service:
public UserAccessDTO Authenticate(AuthenticationDTO authentication)
{
.....
}
I hope the object you are passing in data parameter is same as AuthenticationDTO class, its properties must be same. If that is fine then try running this.
$http.post('url',JSON.stringify(data),{headers: {'Content-Type':'application/json'}})
.success(function (data) {
alert('Success :- '+JSON.stringify(data));
});
As well I am assuming that you have included [HttpPost] attribute before your method. like this:
[HttpPost]
public UserAccessDTO Authenticate(AuthenticationDTO authentication)
{
.....
}

how to add user to openfire by angularjs $http using OF RestApi?

I am using OpenFire Rest APi v 1.2.3 to add new members to it. this is my code to send my request.
var par ={
username:$scope.currentItem.tel1,
password:buildKey($scope.currentItem.password),
name:$scope.currentItem.name,
email: $scope.currentItem.email
};
$http({
method: "POST",
url: baseCfg.xmpp_server + "users",
headers: {
"Content-Type": "application/json",
"Authorization":"Basic YWRtaW46IVFBWjFxYXo="
},
data:JSON.stringify(par)
}).then(function () {
console.log("done");
}, function () {
console.log("error");
});
but I am getting this response :
OPTIONS 403 forbidden
and in request headers there is no headers and parameters.
it was my silly mistake witch i donot turn off my restapi.
i must go to this path an enable it:
OpenFire admin panel > server > server settings > and check Enable

WCF Error 400 (Bad request) when trying to do a POST request in AngularJS

I am using AngularJS and I am trying to do REST CRUD operations with ngresources to a WCF service, but every time I try to do a POST call it gives 400 bad request error. I need to send a json object to the service.
This the factory:
.factory('oncoNotasService', function ($resource) {
return $resource("http://localhost:1046/Rest/Onco_notas_enfermeria.svc/oNCO_NOTAS_ENFERMERIAList", {}, {
query: { method: "GET", isArray: true },
create: { method: "POST"},
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
})
And this is the service WCF:
[OperationContract(Name = "add")]
[WebInvoke(Method = "POST", UriTemplate = "oNCO_NOTAS_ENFERMERIAList/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
ONCO_NOTAS_ENFERMERIADto Add(ONCO_NOTAS_ENFERMERIADto oNCO_NOTAS_ENFERMERIADto);
I don´t know if I am missing something, thank you
I would recommend trying to call the service using a restful client and see if you are getting a 400 response

AngularJs Post to WebApi is always null

Angular Code:
getAuthorizationStatus: function () {
var deferred = $q.defer();
$http({
method: "POST",
url: url,
data: {
username: $scope.username,
password: $scope.password
},
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
},
My Server side code:
[HttpPost]
public int ValidateUser([FromBody]Credentials credentials)
{
try
{
string username = credentials.username;
string password = credentials.password;
//Do stuff
}
catch (Exception ex)
{
throw ex;
return -1;
}
return -1; // not valid user
}
The problem I am having is I am able to hit the Api Method but the data inside is always null. I have tried several combinations like this:
data: JSON.stringify({
"username" : "username",
"password":"mypassword"
}),
No dice.
What am I doing in wrong ?
Enclose your data in $.param()
Example :
data: $.param({ username: $scope.username,password: $scope.password })
I would instead trying to change the default and appropriate behavior of $http's POST, instead let the server read the data from the right place. Taken from MVC controller : get JSON object from HTTP body?:
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
It turns out that MVC doesn't really bind the POST body to any
particular class. Nor can you just fetch the POST body as a param of
the ActionResult (suggested in another answer). Fair enough. You need
to fetch it from the request stream yourself and process it.
Using [FromBody] beside the action input param is enough to get the data from request. Your problem is that you override the content-type in your Angular code through headers:
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //*** Remove this!
}
It must be 'application/json' in order to send json data. Just remove that headers and it should work normally.

Resources