如何将ASP.NET MVC 5中的JSON数据发送回客户端Angular(即在身份验证期间)

时间:2021-12-09 10:32:15

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.

如果经过身份验证,我必须重定向到另一个视图,我需要发送包含AngularJS使用的用户标识和用户名的JSON数据。

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

Redirect有效但我不确定如何将经过身份验证的用户信息作为JSON数据发送到客户端。

Can some one help me?

有人能帮我吗?

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

以下是我在MVC方面的一些代码......

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


    }
}

1 个解决方案

#1


1  

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:

您可以将它放在模型或ViewBag中,如果登录表单实际上是一个页面,那么渲染视图,以及在进行身份验证时重定向到的另一个页面。然后只需使用模型/ ViewBag填充页面/应用程序设置javascript全局或将它们推入角度值或常量,如下所示:

//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...

如果这不是您的意思,并且您正在将表单信息推送为Ajax并且您的Angular实际上是SPA,那么您需要使用AJAX来编组服务器和客户端之间的数据...

Just return a JsonResult like so...

只需返回一个像这样的JsonResult ......

[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>

#1


1  

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:

您可以将它放在模型或ViewBag中,如果登录表单实际上是一个页面,那么渲染视图,以及在进行身份验证时重定向到的另一个页面。然后只需使用模型/ ViewBag填充页面/应用程序设置javascript全局或将它们推入角度值或常量,如下所示:

//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...

如果这不是您的意思,并且您正在将表单信息推送为Ajax并且您的Angular实际上是SPA,那么您需要使用AJAX来编组服务器和客户端之间的数据...

Just return a JsonResult like so...

只需返回一个像这样的JsonResult ......

[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>