简体   繁体   中英

How to send JSON data from ASP.NET MVC 5 back to client side Angular (i.e. during authentication)

i have to redirect to a different view if authenticated and I need to send JSON data containing the userid and username to be used by AngularJS.

The Redirect works but I am not sure how to send the authenticated user information as JSON data to the client-side.

Can some one help me?

Here are some code that I have in MVC side...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TVS.Core.Interfaces;
using TVS.Domain;
using TVS.UI.Models;

namespace TVS.UI.Controllers
{
    public class homeController : Controller
    {


        private readonly IUser _IUser;




        public homeController(IUser IUser)
        {

            _IUser = IUser;

        }




        public ActionResult RedirectAngular()
        {
            return View();
        }
        [HttpGet]

        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]

        public ActionResult Login(UserModel model)
        {

            if (ModelState.IsValid)
            {

                    if (_IUser.IsValidUser(model.Login,model.Password))
                    {

                         FormsAuthentication.SetAuthCookie(model.Login, false);


                        return RedirectToAction("RedirectAngular", "home");


                    }
                    else
                    {
                       // ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                //}
            }



            return View();

        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Login", "home");
        }


    }
}

You could just put it in a model or ViewBag and render the view if the logon form is actually a page and whatever page you redirect to when authenticated is another. Then just use the model / ViewBag to populate a page / app Setting javascript global or push them into angular value or constant like so:

//Controller Action
public ActionResult Logon(string username, string password) {
    //authentication successful...
    //using ViewBag, but model will do as well..
    ViewBag.UserId = 12; //for example...
    ViewBag.UserName = "John Doe";

    return View();
}

@* View
   somewhere near end of <body> tag...
*@

<script src=".../angular.js">
<script>
//or load this from a file...
  angular.module('moduleName', []);
</script>

<script>
  //this need to be in page!!
  angular.moduel('moduleName')
    .value('appSettings', {
        userId : @ViewBag.UserId,
        userName: '@ViewBag.UserName'
    });
</script>

<script>
   //this can be loaded from file...
   angular.controller('controllerName', ctrlFn);
   ctrlFn.$inject = ['$log', 'appSettings'];
   function ctrlFn($log, appSettings) {
      //do something with appSetting here...
      $log.info(appSettings.userId, appSettings.userName);
   }
</script>

If this is not what you meant, and you are pushing the form info as Ajax and your Angular is actually a SPA then you need to use AJAX to marshal data between server and client side...

Just return a JsonResult like so...

[HttpPost]
public ActionResult Logon(string username, string password) 
{
    //authenticate here... assume succesful...
    var user = new { userId = 12, userName = "John Doe" }
    return Json(user, "application/json", Encoding.UTF8);
}

in your angular, just handle whatever getting returned back like so:

<script>
   angular.module('moduleName')
      .factory('loginSvc', svcFn);
   svcFn.$inject = ['$http'];
   function svcFn($http) {
       var svc = { 
          login: login
       };

       return svc;

       function login(username, password) {
          return $http.post(
              '/api/login',
              angular.toJson({username: username, password: password});
       }
   }

   angular.module('moduleName')
        .controller('controllerName', ctrlFn);
   ctrlFn.$inject = ['$log', 'loginSvc'];
   function ctrlFn($log, loginSvc) {
      var self = this;
      self.username = "";
      self.password = "";
      self.login = login;

      function login() {
           loginSvc.login(username, password)
               .then(handleLoginSuccess)
               .catch(handleLoginFailure);
      }

      function handleLoginSuccess(userInfo) {
          $log.info(userInfo); //this should contain logged in user id and username
      }

      //some other functions here...
   }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM