SO, basically I am doing this code to send request to my WebApi controller to invoke a method. My app. is a AngualarJS based, MVC app. For some reason, the web api method is not being hit [as I am trying to inspect it by breakpoints]. I'll post the relevant
code snippets to what I did --
the web api code --
api has route as -----> [RoutePrefix("api/Account")] [Route("RegisterMember")]
[AllowAnonymous]
[HttpPost]
public async Task<IHttpActionResult> Register([FromBody]RegisterVM model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new PetORamaUser()
{
EmailAddress = model.Email,
Password = model.Password
};
if (_appDbContext.PetORamaUsers.Any(x => x.EmailAddress == model.Email))
return Json(new { Success = false, Message = "A user with this email already exists." });
var userIdentity = new AppUser();
userIdentity.Email = model.Email;
userIdentity.UserName = model.Email;
var result = await _userManager.CreateAsync(userIdentity, model.Password);
_appDbContext.PetORamaUsers.Add(new PetORamaUser
{
EmailAddress = model.Email,
IdentityId = userIdentity.Id
});
_appDbContext.SaveChanges();
return Ok("User registered successfully!");
}
(function () {
'use strict';
angular
.module('petApp')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['$scope', '$location', '$timeout', 'AuthService'];
function RegisterController($scope, $location, $timeout, AuthService) {
$scope.savedSuccessfully = false;
$scope.message = "";
$scope.registration = {
email: "",
password: ""
};
$scope.signUpMember = function () {
AuthService.saveRegistration($scope.registration)
.then(function (response) {
$scope.savedSuccessfully = true;
$scope.message = {
success: true,
description: "Registered successfully, you will be redirected to login page shortly"
};
startTimer();
},
function (response) {
var errors = [];
for (var key in response.data.modelState) {
for (var i = 0; i < response.data.modelState[key].length; i++) {
errors.push(response.data.modelState[key][i]);
}
}
$scope.message = {
success: false,
description: "Failed to register user : " + errors.join(' ')
};
});
};
var startTimer = function () {
var timer = $timeout(function () {
$timeout.cancel(timer);
$location.path('/login');
}, 3000);
}
}
})();
the authJs service --
(function () {
'use strict';
angular.module('petApp')
.factory('AuthService', AuthService);
AuthService.$inject = ['$q', '$window', 'errorHandler', '$http', 'tokenHandler'];
function AuthService($q, $window, errorHandler, $http, tokenHandler) {
var serviceBase = 'http://localhost:1234/#!/';
var authServiceFactory = {};
var _saveRegistration = function (registration) {
console.log("Registration called with: " + registration.email + "," + registration.password);
return $http.post('http://localhost:1234/#!/api/Account/RegisterMember', registration)
.then(function (response) {
return response;
});
};
var _login = function (loginData) {
var deferred = $q.defer();
var data = "userName=" + loginData.userName + "&password=" + loginData.password + "&grant_type=password";
$http.post(serviceBase + 'token', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function (result) {
tokenHandler.setLoginToken(result.access_token);
tokenHandler.setLoginName(result.userName);
deferred.resolve(result);
})
.error(function (err, status) {
_logOut();
deferred.reject(err);
});
return deferred.promise;
};
var _logOut = function () {
var deferred = $q.defer();
$http.post('/api/Account/Logout')
.success(function (response) {
tokenHandler.removeLoginToken();
deferred.resolve(response);
})
.error(function (err, status) {
_logOut();
deferred.reject(err);
});
return deferred.promise;
};
var _isAuthenticated = function () {
return tokenHandler.hasLoginToken();
}
authServiceFactory.saveRegistration = _saveRegistration;
authServiceFactory.login = _login;
authServiceFactory.logOut = _logOut;
authServiceFactory.isAuthenticated = _isAuthenticated;
return authServiceFactory;
}
})();
I configured my webapiconfig file as --
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.EnsureInitialized();
config.Routes.MapHttpRoute(
name: "APIRoute",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var formatters = config.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
PS - my application is not 'pretty routed' yet. So the url loads like --- localhost:1234/#!, localhost:1234/#!/register ......... and so on.
So why isn't the webapi breakpoint reached? I used the console.log to make sure it is picking up values from the input fields. I tried some other variations of the webapi routes in the apiconfig file. I haven't posted them all in this question. But they haven't
yielded my purpose either. So where am I going wrong? What are the problems in my code that you can see? Kindly point me towards something at least. Any kind of help on this would be very great for me.
Thanks in advance,
There are more wonders in this world of ours than you can wonder; and it is nice to sometimes wonder at them.
According to your description, we couldn't directly find the reason why your web api controller doesn't work.
There are multiple reasons.
For example:
1.Your angualr js codes doesn't send the request.
2.The web api method url is wrong.
I suggest you could firstly use the browser develop tool to check the status of request which is sent from the angualr to your web api.
Then we could locate the issue with the request status.
Best Regards,
Brando
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Did you add some special setting in the web api route config?
Best Regards,
Brando
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
No, it appears that the request is not at all going to the api!! That is so strange!!
Kindly see the image for reference: pasteboard.co/HlCaB22.png
Furthermore it's now giving a whole new error on registerController that it wasn't giving before. [kindly take a look at the registerController.cs code I posted earlier]. I didn't add or change any code there in the meanwhile! error: cannot read property 'then' .... ...
This is behaving so weirdly now!
Thanks,
There are more wonders in this world of ours than you can wonder; and it is nice to sometimes wonder at them.
your image explains all. your post is to http://localhost:1234 and its returning html. if you have the default setup, this is returning your default document. you should pass the correct url to your ajax call and it will
probably work.
Member
51 Points
307 Posts
Unable to reach WebAPI POST method from angularJS function call ---
May 14, 2018 05:39 PM|PGChoudhury|LINK
SO, basically I am doing this code to send request to my WebApi controller to invoke a method. My app. is a AngualarJS based, MVC app. For some reason, the web api method is not being hit [as I am trying to inspect it by breakpoints]. I'll post the relevant code snippets to what I did --
the web api code --
my html form template --
my register controller --
the authJs service --
I configured my webapiconfig file as --
and my global.asax --
PS - my application is not 'pretty routed' yet. So the url loads like --- localhost:1234/#!, localhost:1234/#!/register ......... and so on.
So why isn't the webapi breakpoint reached? I used the console.log to make sure it is picking up values from the input fields. I tried some other variations of the webapi routes in the apiconfig file. I haven't posted them all in this question. But they haven't yielded my purpose either. So where am I going wrong? What are the problems in my code that you can see? Kindly point me towards something at least. Any kind of help on this would be very great for me.
Thanks in advance,
Star
9831 Points
3120 Posts
Re: Unable to reach WebAPI POST method from angularJS function call ---
May 15, 2018 07:32 AM|Brando ZWZ|LINK
Hi PGChoudhury,
According to your description, we couldn't directly find the reason why your web api controller doesn't work.
There are multiple reasons.
For example:
1.Your angualr js codes doesn't send the request.
2.The web api method url is wrong.
I suggest you could firstly use the browser develop tool to check the status of request which is sent from the angualr to your web api.
Then we could locate the issue with the request status.
Best Regards,
Brando
Member
51 Points
307 Posts
Re: Unable to reach WebAPI POST method from angularJS function call ---
May 15, 2018 03:05 PM|PGChoudhury|LINK
Hi.
Did it. This is what I have currently. Kindly see the image. --
pasteboard.co/Hlj1OZy.png
Apparently the status is 200, means OK for the request. Which one do I check next?
Thanks,
Star
9831 Points
3120 Posts
Re: Unable to reach WebAPI POST method from angularJS function call ---
May 16, 2018 02:18 AM|Brando ZWZ|LINK
Hi PGChoudhury,
According to your image, I couldn't find the details url information for the request.
I suggest you could firstly check the request url is right which sent by clicking the sign up button.
Like this:
Besides, I found the url you want to access is strange.
Why you add "#!" in the url?
Did you add some special setting in the web api route config?
Best Regards,
Brando
Member
51 Points
307 Posts
Re: Unable to reach WebAPI POST method from angularJS function call ---
May 17, 2018 03:51 PM|PGChoudhury|LINK
Hi again,
No, it appears that the request is not at all going to the api!! That is so strange!!
Kindly see the image for reference: pasteboard.co/HlCaB22.png
Furthermore it's now giving a whole new error on registerController that it wasn't giving before. [kindly take a look at the registerController.cs code I posted earlier]. I didn't add or change any code there in the meanwhile!
error: cannot read property 'then' .... ...
This is behaving so weirdly now!
Thanks,
All-Star
58254 Points
15675 Posts
Re: Unable to reach WebAPI POST method from angularJS function call ---
Jun 05, 2018 03:30 PM|bruce (sqlwork.com)|LINK
your image explains all. your post is to http://localhost:1234 and its returning html. if you have the default setup, this is returning your default document. you should pass the correct url to your ajax call and it will probably work.
looking at your code you have:
the browser will not include any path data after a # in a request, so your code is the same as: