侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Asp.net MVC利用knockoutjs实现登陆并记录用户的内外网IP及所在城市(推荐)

前端  /  管理员 发布于 7年前   242

前言

前面第一篇开了头个,现在想先从登陆写起,但感觉还有很多东西应该放在前面写,比如

1、MVC及Web API的Route配置,Web API的Route配置如何支持命名空间

2、如何配置Filters(实现安全验证、错误处理等等)

3、自定义Filters、HttpRouteConstraint、ModelBinder及HttpParameterBinding等

这些问题在我开发过程中都有碰到,但感觉每一点都要说太多了。如果有需要到时候再回过头来写。

需求

还是老样子,我们先要明白要登陆实现哪些东西:

1、登陆页面(用户名、密码、记住我、登陆按钮、重置按钮)

2、消息显示(比如 错误时显示某某错误,登陆时显示正在登陆,登陆成功显示正在跳转等)

3、登陆处理(验证、登陆、正在登陆时禁用表单、更新用户登陆次数及时间、添加登陆履历其中要包括用户的内网IP外网IP还有所在城市、其它业务处理)

4、成功跳转

实现效果

在实现之前我们先看看实现出来的效果截图

登陆页面

跳转页面

登陆履历

需求分析及实现

需求中基本都好实现,只有登陆履历中要记录内外网IP及所在城市要考虑一下。在asp.NET中取得客户端内外网IP还是比较麻烦的,而要取得所在城市就基本不可能了,所以我们只好考虑借助第三方api去实现了。

1、内网IP直接在后台取

2、外网IP可以通过新浪API http://counter.sina.com.cn/ip 取得,原来也可以返回城市的,后台不知道什么原因,只能返回IP了

3、所在城市通过百度API http://api.map.baidu.com/location/ip?ak=&ip=取得,但是这个不会返回外网IP所以我就两个一起用了,挺蛋疼的。

以上在客户端去访问相应的API又存在一个跨域的问题,通过调查发现百度API支持JSONP,可以很好的解决跨域的问题,新浪API不支持但它返回一个变量,我们可以直接把新浪API写在页面srcipt中即可取得相应变量。

技术都应该没问题了,那我们开始写吧。

具体实现

第一步:在MVC中新建LoginController添加如下代码

using System;using System.Web.Mvc;using Newtonsoft.Json;using Newtonsoft.Json.Linq;using Zephyr.Core;using Zephyr.Models;using Zephyr.Web.Areas.Mms.Common;namespace Zephyr.Controllers{ [AllowAnonymous] public class LoginController : Controller { public ActionResult Index() { ViewBag.CnName = "建筑材料管理系统"; ViewBag.EnName = "Engineering Material Mangange System"; return View(); } }}

类要用AllowAnonymous属性修饰,才能保证未登陆也能够访问。

第二步:添加对应的View,添加~/Views/Login/Index.cshtml,代码如下

@{ ViewBag.Title = "登录系统"; Layout = null;}<!doctype html><html> <head> <title>@ViewBag.Title</title> <link href="https:/article/~/Content/css/page/login.css" rel="stylesheet" type="text/css" /> <script src="https:/article/~/Content/js/jquery/jquery-1.8.1.min.js"></script> <script src="https:/article/~/Content/js/core/json2.js"></script> <script src="https:/article/~/Content/js/core/knockout-2.2.1.js"></script> <script src="https:/article/~/Content/js/viewModel/login.js"></script> <script src="http://counter.sina.com.cn/ip"></script> </head> <body> <div class="second_body"> <form data-bind="submit:loginClick"> <div class="logo"><img src="https:Content/images/login/logo.png" alt="" /></div> <div class="title-zh">@ViewBag.CnName</div> <div class="title-en" style="@ViewBag.EnNameStyle">@ViewBag.EnName</div> <div class="message" data-bind="html:message"></div> <table border="0" style="width:300px;">  <tr>  <td style="padding-bottom: 5px;width:55px;">用户名:</td>  <td colspan="2"><input type="text" class="login" data-bind="value:form.usercode" /></td>  </tr>  <tr>  <td class="lable" style="letter-spacing: 0.5em; vertical-align: middle">密码:</td>  <td colspan="2"><input type="password" class="login" data-bind="value:form.password" /></td>  </tr>  <tr>  <td></td>  <td colspan="2"><input type="checkbox" data-bind="checked:form.remember" /><span>系统记住我</span></td>  </tr>  <tr>  <td colspan="3" style="text-align:center">  <input type="submit" value="登录" class="login_button" />  <input type="button" value="重置" class="reset_botton" data-bind="click:resetClick" />  </td>  </tr> </table> </form> </div> </body></html>

1、脚本的最后一个即添加新浪API获取外网IP信息,它返回的数据格式为

var ILData = new Array("117.30.94.103","保留地址", "", "", ""); if (typeof(ILData_callback) != "undefined") { ILData_callback(); }

它其实也有一个callback函数,和JSONP类似,但函数名是固定的,并且没有传递数据。我们可以直接访问ILData[0]取得外网IP。

2、上面html中的data-bind=””写法为knouckoutjs的写法,用于绑定到viewModel的属性

第三步:创建ViewModel

var viewModel = function () { var self = this; this.form = { usercode: ko.observable(), password: ko.observable(), remember:ko.observable(false), ip: null, city: null }; this.message = ko.observable(); this.loginClick = function (form) { $.ajax({ type: "POST", url: "/login/doAction", data: ko.toJSON(self.form), dataType: "json", contentType: "application/json", success: function (d) { if (d.status == 'success') {  self.message("登陆成功正在跳转,请稍候...");  window.location.href = '/'; } else {  self.message(d.message); } }, error: function (e) { self.message(e.responseText); }, beforeSend: function () { $(form).find("input").attr("disabled", true); self.message("正在登陆处理,请稍候..."); }, complete: function () { $(form).find("input").attr("disabled", false); } }); }; this.resetClick = function () { self.form.usercode(""); self.form.password(""); self.form.remember(false); }; this.init = function () { self.form.ip = ILData[0]; $.getJSON("http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&callback=?", function (d) { self.form.city = d.content.address; }); if (top != window) top.window.location = window.location; }; this.init();};$(function () { ko.applyBindings(new viewModel());});

定义viewModel,其属性包括from表单信息,message提示信息,loginClick登陆,resetClick重置。其中的init部分其实可以不放到viewModel中。

1、$.getJSON即为JSONP的访问,其中加上了参数callback=?,jQuery会自动处理成当前的回调函数,即跨域成功后会自动回调当前函数并传入数据。我们用viewModel中的form.city接收请求的数据中的城市信息。

2、最后一句ko.applyBindings(new viewModel())即实现了页面和viewModel的绑定,至此,前台全部完成。接下来写登陆处理doAction,还是放在LoginController中,访问地址为/login/doAction。

第四步:在LoginController中添加doAction的方法返回JSON数据。代码如下:

public JsonResult DoAction(JObject request){ var message = new sys_userService().Login(request); return Json(message, JsonRequestBehavior.DenyGet);}

然后在service层中处理

using System;using System.Collections.Generic;using Zephyr.Core;using System.Dynamic;using Newtonsoft.Json.Linq;using Newtonsoft.Json;using Zephyr.Utils;using Zephyr.Web.Areas.Mms.Common;namespace Zephyr.Models{ public class sys_userService : ServiceBase<sys_user> { public object Login(JObject request)  { var UserCode = request.Value<string>("usercode"); var Password = request.Value<string>("password"); //用户名密码检查 if (String.IsNullOrEmpty(UserCode) || String.IsNullOrEmpty(Password)) return new { status = "error", message = "用户名或密码不能为空!" }; //用户名密码验证 var result = this.GetModel(ParamQuery.Instance()  .AndWhere("UserCode", UserCode)  .AndWhere("Password", Password)  .AndWhere("IsEnable", true)); if (result == null || String.IsNullOrEmpty(result.UserCode)) return new { status = "error", message = "用户名或密码不正确!" }; //调用框架中的登陆机制 var loginer = new LoginerBase { UserCode = result.UserCode, UserName = result.UserName }; FormsAuth.SignIn(loginer.UserCode, loginer, 60 * 8);  //登陆后处理 this.UpdateUserLoginCountAndDate(UserCode); //更新用户登陆次数及时间 this.AppendLoginHistory(request); //添加登陆履历 MmsService.LoginHandler(request); //MMS系统的其它的业务处理 //返回登陆成功 return new { status = "success", message = "登陆成功!" }; } //更新用户登陆次数及时间 public void UpdateUserLoginCountAndDate(string UserCode) { db.Sql(@"update sys_userset LoginCount = isnull(LoginCount,0) + 1 ,LastLoginDate = getdate()where UserCode = @0 " , UserCode).Execute(); } //添加登陆履历 public void AppendLoginHistory(JObject request) { var lanIP = ZHttp.ClientIP; var hostName = ZHttp.IsLanIP(lanIP) ? ZHttp.ClientHostName : string.Empty; //如果是内网就获取,否则出错获取不到,且影响效率 var UserCode = request.Value<string>("usercode"); var UserName = MmsHelper.GetUserName(); var IP = request.Value<string>("ip"); var City = request.Value<string>("city"); if (IP != lanIP) IP = string.Format("{0}/{1}", IP, lanIP).Trim('/').Replace("::1", "localhost"); var item = new sys_loginHistory(); item.UserCode = UserCode; item.UserName = UserName; item.HostName = hostName; item.HostIP = IP; item.LoginCity = City; item.LoginDate = DateTime.Now; db.Insert<sys_loginHistory>("sys_loginHistory", item).AutoMap(x => x.ID).Execute(); } }}

接收参数定义为JObject对象比较方便取得请求数据,数据服务中的GetModel是服务基类中已有的方法,这当中用到了两个函数,一个为UpdateUserLoginCountAndDate为更新用户登陆次数及时间的处理,另一个AppendLoginHistory添加登陆履历。至此已大功告成!

以上所述是小编给大家介绍的Asp.net MVC利用knockoutjs实现登陆并记录用户的内外网IP及所在城市(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!


  • 上一条:
    详解ASP.NET提取多层嵌套json数据的方法
    下一条:
    详解ASP.NET Core 在 JSON 文件中配置依赖注入
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 使用 Alpine.js 排序插件对元素进行排序(0个评论)
    • 在js中使用jszip + file-saver实现批量下载OSS文件功能示例(0个评论)
    • 在vue中实现父页面按钮显示子组件中的el-dialog效果(0个评论)
    • 使用mock-server实现模拟接口对接流程步骤(0个评论)
    • vue项目打包程序实现把项目打包成一个exe可执行程序(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-03
    • 2018-04
    • 2018-05
    • 2018-06
    • 2018-09
    • 2018-11
    • 2018-12
    • 2019-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客