Angular controller doesn't pass value to web api method with $http - angularjs

This is my angularjs code:
var uname = resetPasswordRequestData.email
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: uname
});
web api code:
public class PerformPasswordResetController : ApiController
{
public int PerformResetPassword([FromBody]string uname)
{
CrmUser contact = null;
if (ModelState.IsValid)
{
try
{
contact = new PasswordResetProvider().GetUserByName(uname);
}
catch (Exception ex)
{
return 1;
}
}
}
My problem is when I make the call from Fiddler it works, but when I run the code it nicely rout to the web api method but in web api controller "uname" argument is null. when I pass some data from fiddler it pass that data to "uname" (in web api controller uname is not null)
can anyone help me?

I strongly suggest you use a Model class to receive the data on your server.
Something like this:
public class UserModel {
public string UserName { get; set; }
}
public class PerformPasswordResetController : ApiController
{
public int PerformResetPassword([FromBody]UserModel user)
{
...Do your stuff
}
}
And on your angular code:
var model = {
userName: resetPasswordRequestData.email
};
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: model
});
Also, if you don´t want (or can´t) change your server code, try this please:
var uname = resetPasswordRequestData.email
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: {
uname: uname
}
});

Related

angularJS post CORS

I am new to AngularJS and still learning. I have this angularJS code below to check my log-in credentials in my API. But upon log-in(clicking my log-in button) it does not hitting my break point in my API Code. Both API and Log-in codes are running from my local machine. I attached the picture for the CORS error.
AngularJS
data = {username:'user', password:'pass' }
app.service('services', function ($http, $window) {
services = {};
//Set the link once in upon open of project
localStorage.setItem('link', 'http://localhost:63763/');
var surl = localStorage.getItem('link');
services.signin = function (data) {
var result = $http({
method: 'POST',
url: surl + 'api/auth/signin', data: data,
}).then(function (response) {
return response;
}, function (err) {
return err;
});
return result;
};
return services;
});
API
[HttpPost]
[Route("signin")]
public IHttpActionResult Authenticate([FromBody] UsersSigninDTO dto)
{
//Codes
}
Class DTO
public class UsersSigninDTO
{
[Required(ErrorMessage = "username is required.")]
public string username { get; set; }
[Required(ErrorMessage = "password is required.")]
public string password { get; set; }
}
[Error Picture]
I solve it. On API Code side I added these code under the WebApiConfig.cs
config.MapHttpAttributeRoutes();
EnableCorsAttribute CorsAttribute = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(CorsAttribute);
You are using 2 different ports when calling localhost, thus triggering CORS.
App seems to be loaded from localhost:51216 and the requests to API by localhost:63763
What if you load your app from localhost:63763 ?
Maybe you are running 2 webpack instances at the same time? Check your config.

POST request not getting mapped to Spring MVC Controller

I am sending a POST request from Angularjs $http service . It is working fine when my promise is like below and is getting properly mapped to Spring Controller ,
service.js
reassignKsaPendingLeads : function(data,username)
{
var promise = $http({
url : "reassignPendingLeads.htm",
method : "POST",
data : mydata
})
.success(function(data, status, header, config, statusText)
{
}
}
Spring Controller
#RequestMapping({ "reassignPendingLeads.htm" })
public #ResponseBody String updateAccessStatus(#RequestBody List<KsaLead> ksaLeads)
{
log.info("Inside updateAccessStatus");
return "true";
}
The json object i pass from service.js is getting mapped properly to #RequestBody List ksaLeads.
Since the json object contains same keys as bean properties of KsaLead.
But Now i want to pass another parameter username apart from json body (data).
Then i get Request method 'POST' not supported in Spring Controller .
new service.js
reassignKsaPendingLeads : function(data,username)
{
var mydata = JSON.stringify(data) + '&username=' + username;
var promise = $http({
url : "reassignPendingLeads.htm",
method : "POST",
data : mydata
})
.success(function(data, status, header, config, statusText)
{
}
new Spring Controller
#RequestMapping({ "reassignPendingLeads.htm" })
public #ResponseBody String updateAccessStatus(#RequestBody List<KsaLead> ksaLeads,#RequestParam String username)
{
log.info("Inside updateAccessStatus");
return "true";
}
Can anyone guide me as to how should i pass data from angularJs so that it gets mapped correctly to Spring Controller
I would assume that you want to pass the username as a request parameter. In order to do this, the $http can have a params input field:
function(data,username) {
var promise = $http({
url: "reassignPendingLeads.html",
method: "POST",
data: data,
params: { username: username }
})
// continue with your promise here
}
If you want to pass it inside the request body we have to do the following steps:
We have to add the username to the mydata object.
// we assume that data is not a primitive type
function(data,username) {
var mydata;
// check if data is defined
if (data) {
// make a deep copy first, since we don't want to modify the input
mydata = angular.copy(data);
} else {
// if the data is undefined, create e new object
mydata = {};
}
// add the username to mydata
mydata.username = username;
var promise = $http({
url: "reassignPendingLeads.html",
method: "POST",
data: mydata
})
// continue with your promise here
}
On the back-end we have to make sure that we can accept this kind of data. For this it is advised to create a data class which holds the username and any other fields which may appear on your data object from the front-end.
Probably something like this:
public class MyDataClass {
private String username;
// other fields
// no args constructor
public MyDataClass() {}
// all args constructor
public MyDataClass(String username) {
this.username = username;
}
// getter and setters
}
Now we modify the controller to accept it:
#RequestMapping(value = "reassignPendingLeads.htm", method = RequestMethod.POST)
public #ResponseBody String updateAccessStatus(#RequestBody MyDataClass data)
{
log.info(data.getUsername());
return "true";
}

Not hitting with Web API two different GET methods

Implemented webapi routing and having two different route methods for for retrieving values but it is differentiated by supplying parameter type.
Api methods are getting hit for the corresponding action methods if we simply specify "apiurl/api/contact/search/sri" and "apiurl/api/contact/get/2" in direct browser url.
But when comes to communicate with angular to webapi, api is not getting hit.
//angular service
contact.search = function (inputName) {
return $http({
method: 'GET',
url: url + 'api/contact/search',
//params: { name: inputName }
data: { name: inputName }
});
//return $http.get(url + 'api/contact/search', name);
}
//WebAPI
[HttpGet]
[Route("search/{name:alpha}")]
public IHttpActionResult GetContacts([FromBody]string name)
{
repository = new ContactRepository();
if (string.IsNullOrEmpty(name))
{
var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Search Name can not be empty")
};
throw new HttpResponseException(message);
}
return Ok(repository.GetContact(name));
}
// GET api/contact/5
[HttpGet]
[Route("get/{id:int}")]
public IHttpActionResult Get(int id)
{
repository = new ContactRepository();
if (id == 0)
{
var message = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Issue with Passed Id Parameter.") };
throw new HttpResponseException(message);
}
return Ok(repository.GetContact(id));
}
When you use data: { name: inputName }, it is appended to the url in the following way:
...api/contact/search?name=inputName
but what you want is this:
...api/contact/search/inputName
So, you have two options.
Either change your angular code:
return $http({
method: 'GET',
url: url + 'api/contact/search/' + inputName,
});
or change your API to accept QUERY params.
Hope it helps

$http.post request can't find method in controller

I have a AddCategory() method in my Controller:
[RoutePrefix("api")]
public class CategoryController : ApiController
{
....
[Route("addCategory")]
[HttpPost]
public void AddCategory(string category)
{
var getCat = category;
}
At the my Home.html i have button Save New Category i wrote the $http.post method for it:
var testString = "TEST String";
var req = {
method: 'POST',
url: '/api/addCategory',
data: testString,
};
$http(req).then(function successCallback(response) {
console.log("Success");
}, function errorCallback(response) {
console.log("Eror");
});
But i have the next error:
angular.js:11442 POST http://localhost:6059/api/addCategory 404 (Not
Found)
At the Network bookmark in Development console i finded the error:
may be it's important but i disabled XML in WebApiConfig.cs:
var json = GlobalConfiguration.Configuration.Formatters;
json.JsonFormatter.UseDataContractJsonSerializer = true;
json.Remove(json.XmlFormatter);
May be somebody knows how i can change it ? Thanks for your answers!
You method Post need to return IHttpActionResult. or your request http always returns code 404.
Try this :
[RoutePrefix("api")]
public class CategoryController : ApiController
{
....
[Route("addCategory")]
[HttpPost]
public IHttpActionResult AddCategory(string category)
{
var getCat = category;
if(getCat != null)
return Ok();
return NotFound();
}
I advice you to use Api Rest in C# with $resource angular. In my mind, it's the best pattern.
The problem is related to the service you are calling, 404 means not found:
404 http error
therefore something in the service URL or in your local server is not working.

400 Bad Request when accessing a Sprint Rest method with AngularJs

I am trying to access an update rest method with AngularJs, but it is giving me 400 bad request error.
Here is my code.
#RestController
#RequestMapping("/api/loggedInUser")
public class UserController {
#RequestMapping(value = "/{id}",method = RequestMethod.PUT)
public AppUser updateLoggedInUser(#RequestBody AppUser user){
return userService.updateAppUser(user);
}
}
Here is the code for accessing the service from AngularJs:
App.factory('LoggedInUserService', ['$resource', function($resource) {
console.log('service injected');
return {
getLoggedInUser: $resource('api/loggedInUser', {}, {
query: {method: 'GET'}
}),
updateLoggedInUser: $resource('api/loggedInUser/:id', {}, {
update: {method: 'PUT', params: {id: '#id'}}
})
};
}]);
Here is the code for accessing the service in my app.js file.
.run(function($location, $rootScope, LoggedInUserService) {
LoggedInUserService.getLoggedInUser.query(function(loggedInUser) {
$rootScope.loggedInUser = loggedInUser;
console.log($rootScope.loggedInUser.username);
if (loggedInUser.role[0].authority === 'ADMIN_ROLE' && loggedInUser.pristineAccess) {
$rootScope.loggedInUser.isAdmin = true;
$rootScope.pristineAccess = false;
LoggedInUserService.updateLoggedInUser.update($rootScope.loggedInUser);
$location.path('/admin');
} else {
$rootScope.loggedInUser.isAdmin = false;
$location.path('/dashboard');
}
});
});
When I remove the #RequestBody annotation I don't get a 400 error but the parameter doesn't get populated.
What am I doing wrong here? I used the same kind of code in another place in the same application and it worked fine. The only difference here is that the rest method argument parameter is an entity object and not a pojo.
add consumes = MediaType.APPLICATION_JSON_VALUE to your controller method and check your POST content with web developers tool or firebug or simmilar tool
#RequestMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.PUT)
public AppUser updateLoggedInUser(#RequestBody AppUser user){
return userService.updateAppUser(user);
}

Resources