简体   繁体   English

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

[英]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. 如果经过身份验证,我必须重定向到其他视图,并且我需要发送包含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");
        }


    }
}

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. 如果登录表单实际上是页面,而您在身份验证后重定向到的任何页面都是另一个页面,则可以将其放在模型或ViewBag中并呈现视图。 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来填充页面/应用设置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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET MVC 4-将JSON数据从客户端的任何页面发布到服务器 - ASP.NET MVC 4 - posting JSON data from any page on the client side to the server 将JSON数据从Sencha Touch发送到ASP.NET MVC - Send JSON data from Sencha Touch to ASP.NET MVC 如何使用Response对象将Json数据从标准ASP.NET WebForm传递回客户端? - How do I pass Json data back to the client from a standard ASP.NET WebForm using the Response object? 如何将 JSON 数组从服务器发送到客户端,即(java 到 AJAX/Javascript)? - How to send JSON array from server to client, i.e. (java to AJAX/Javascript)? 如何在asp.net中发回JSON? - How to send back JSON in asp.net? Asp.net MVC:在Json对象内发送回HTML - Asp.net MVC: Send back HTML inside Json object 如何将自定义字符串与json数据一起发送到asp.net mvc控制器? - How would I send custom string with json data to asp.net mvc controller? 如何一次性将Angular中的json数据和formdata(文件)发送到ASP.NET WebAPI Controller操作? - How to send json data and formdata (files) from Angular to an ASP.NET WebAPI Controller action in one shot? 如何: (a) 从浏览器发送 JSON 数据到 controller; (b) 将转换后的数据发送到 ASP.NET MVC 中的 SQL 服务器? - How to: (a) send JSON data from the browser to the controller; and (b) send the transformed data to SQL Server within ASP.NET MVC? 在ASP.NET应用程序的客户端中读取Json数据 - Json data reading in client side in asp.net application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM