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.
Related
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.
I am a newbie to angularjs. I am trying to send a json object in $http.put request as follows:
function LoginCtrl($http){
this.login = function(){
var self = this;
self.user = {
username: this.username,
password: this.password
}
$http.put('http://localhost:8086/app/login',self.user).then(function
successCallback(response) {
}, function errorCallback(response) {
})
}
}
I just want to get this json object in Rest api, the code of which is as follows:
#Path("/app")
public class LoginResource {
public LoginResource() {
}
#PUT
#Path("/login")
#Consumes(MediaType.APPLICATION_JSON)
public Response getUserByName() {
return Response.status(Response.Status.ACCEPTED).build();
}
What parameters i need to pass to this getUserByName api?. I am using dropwizard
Also if somebody could tell how to set the index.html page as the starting page in jetty server config.
First, in your Dropwizard(Jersey) backend define your input
public Response getUserByName(User user) { ...
Then you can map your JSON to an entity like this:
public class User {
#JsonProperty("name")
private String name; }
In angularJS pass the Json object as a request payload in $http.PUT(uri,<JsonObject>)
http.put(url, JSON.stringify(self.user), function (err, response)
{
// do something here
}
I have a problem. I have this dropdown list :
#Html.DropDownListFor(m => m.SelectCountryId, Model.Countries, #Translator.Translate("PLEASE_SELECT"), new { id = "CountryID", #class = "form-control",ng_model="countryId", ng_change = "LoadRegions(countryId);", #required = "required" })
And i need on ng_change to get into MVC controller that looks like this:
[AllowAnonymous]
public JsonResult GetRegions(int countryId) // return a JsonResult
{
IUserManager manager = UserFactory.GetUserManager(WebConfiguration.DefaultTerminalId);
var model = manager.GetRegions(countryId);
return Json(model, JsonRequestBehavior.AllowGet);
}
This is script in angular:
$scope.LoadRegions = function (countryId)
{
console.log("COUNTRY ID: ", countryId);
$http.post('/app/Account/GetRegions/'+ countryId).then(function (response)
{
alert(response);
});
}
I get country ID but in console i get this error:
POST http://localhost:60789/app/Account/GetRegions/4 500 (Internal Server Error)
The default routing in MVC allows for {controller}/{action}/{id} but your controller is expecting {controller}/{action}/{countryId}.
You can change your call to look like:
GetRegions?countryId=XXX
Or change your method signature to look like:
public JsonResult GetRegions(int id)
Or, if you really want to, you can accommodate this route in your RouteConfig.cs
Edit: I just realized you're calling this with $http.post but everything in your code suggests you want this to be a GET, so I'd change your angular code to $http.get()
From the looks of it there are a few problems in your javascript.
Try the following.
$scope.LoadRegions = function (countryId)
{
var params = {};
params.countryId = countryId;
console.log("COUNTRY ID: ", countryId);
$http.post('/Account/GetRegions/', params).then(function (response)
{
alert(response);
});
}
As you can see you're passing in the params object with the country ID, you are making a call to the POST on the server side also -> Seperate to the angular app folder.
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
}
});
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);
}