locked
Unable to reach WebAPI POST method from angularJS function call --- RRS feed

  • Question

  • User-215451226 posted

    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!"); }

    my html form template --

    <form name="registrationForm" method="post" novalidate class="form-horizontal">
                        <div class="form-group">
                            <div class="col-md-offset-2">
                                <h4>
                                    <strong>
                                        {{message.description}}
                                    </strong>
                                </h4>
                            </div>
                        </div>
    
                        <div class="form-group" style="text-align:center">
                            <div class="row">
                                <input type="email" ng-model="registration.email" style="width:285px; border-radius:3px" required name="email" value="" placeholder="Email ....">
                                <p ng-show="registrationForm.email.$invalid && !registrationForm.email.$pristine" class="help-block">A valid email is required.</p>
                            </div>
                        </div>
    
    
                        <div class="form-group" style="text-align:center">
                            <div class="row">
                                <input type="password" ng-model="registration.password" style="width:285px; border-radius:3px" name="password" value="" required placeholder="Password ....">
                                <p ng-show="registrationForm.password.$invalid && !registrationForm.password.$pristine" class="help-block">A Password of at least 6 characters is required. </p>
                            </div>
                        </div>
    
                        <div class="form-group" style="text-align:center">
                            <div class="row">
                                <input class="ui huge teal fluid button ember-view" type="submit" ng-disabled="registrationForm.$invalid" ng-click="signUpMember()" name="submit" value="Sign Up" style="color:white">
                                <input class="ui huge teal fluid button ember-view" type="button" id="cnclBtn" ng-click="cancelClicked()" name="Cancel" value="Cancel" style="background-color:lightgreen; color:darkblue" />
                            </div>
                        </div>
                                            
                        
                    </form>

    my register controller --

    (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();
            }
        }

    and my global.asax --

    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                GlobalConfiguration.Configure(WebApiConfig.Register);
            }

    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, 




    Monday, May 14, 2018 5:39 PM

Answers

  • User-474980206 posted

    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:

                return $http.post('http://localhost:1234/#!/api/Account/RegisterMember', registration)

    the browser will not include any path data after a # in a request, so your code is the same as:

                return $http.post('http://localhost:1234/', registration)
    
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 5, 2018 3:30 PM

All replies

  • User283571144 posted

    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

    Tuesday, May 15, 2018 7:32 AM
  • User-215451226 posted

    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,

    Tuesday, May 15, 2018 3:05 PM
  • User283571144 posted

    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.

    http://localhost:1234/#!/api/Account/RegisterMember

    Why you add "#!" in the url?

    Did you add some special setting in the web api route config?

    Best Regards,

    Brando

    Wednesday, May 16, 2018 2:18 AM
  • User-215451226 posted

    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,

    Thursday, May 17, 2018 3:51 PM
  • User-474980206 posted

    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:

                return $http.post('http://localhost:1234/#!/api/Account/RegisterMember', registration)

    the browser will not include any path data after a # in a request, so your code is the same as:

                return $http.post('http://localhost:1234/', registration)
    
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 5, 2018 3:30 PM