Asp.net MVC利用knockoutjs實現登陸並記錄使用者的內外網路IP及所在城市

高洛峰
發布: 2017-02-10 17:21:49
原創
1486 人瀏覽過

這篇文章主要介紹了Asp.net MVC利用knockoutjs實現登陸並記錄用戶的內外網IP及所在城市(推薦),需要的朋友可以參考下

前言

前面第一篇開了頭個,現在想先從登陸寫起,但感覺還有很多東西應該放在前面寫,例如

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

2、如何配置Filters(實現安全驗證、錯誤處理等等)

3、自訂Filters、HttpRouteConstraint、ModelBinder及HttpParameterBinding等

這些問題在我開發過程中都碰到,但感覺每一點都要說太多了。如果有需要到時候再回過頭來寫。

需求

還是老樣子,我們先要明白要登陸實現哪些東西:

1、登陸頁(用戶名、密碼、記住我、登陸按鈕、重置按鈕)

1、登陸頁(用戶名、密碼、記住我、登陸按鈕、重設按鈕)

2、訊息顯示(例如錯誤時顯示某某錯誤,登陸時顯示正在登陸,登陸成功顯示正在跳轉等)

3、登陸處理(驗證、登陸、正在登陸時禁用表單、更新用戶登陸次數及時間、添加登陸履歷其中要包含用戶的內網IP外網IP還有所在城市、其它業務處理)

4、成功跳轉實現效果

在實現之前我們先看看實現出來的效果截圖

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

跳轉頁Asp.net MVC利用knockoutjs实现登陆并记录用户的内外网IP及所在城市

登陸履歷Asp.net MVC利用knockoutjs实现登陆并记录用户的内外网IP及所在城市

登陸履歷

。外網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();
 }
 }
}
登入後複製

類要用Allowonymous

第二步:新增對應的View,新增~/Views/Login/Index.cshtml,程式碼如下

@{
 ViewBag.Title = "登录系统";
 Layout = null;
}
<!doctype html>
<html>
 <head>
 <title>@ViewBag.Title</title>
 <link href="~/Content/css/page/login.css" rel="stylesheet" type="text/css" />
 <script src="~/Content/js/jquery/jquery-1.8.1.min.js"></script>
 <script src="~/Content/js/core/json2.js"></script>
 <script src="~/Content/js/core/knockout-2.2.1.js"></script>
 <script src="~/Content/js/viewModel/login.js"></script>
 <script src="http://counter.sina.com.cn/ip"></script>
 </head>
 <body>
 <p class="second_body">
 <form data-bind="submit:loginClick">
 <p class="logo"><img src="/Content/images/login/logo.png" alt="" /></p>
 <p class="title-zh">@ViewBag.CnName</p>
 <p class="title-en" style="@ViewBag.EnNameStyle">@ViewBag.EnName</p>
 <p class="message" data-bind="html:message"></p>
 <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>
 </p>
 </body>
</html>
登入後複製

1、腳本的最後一個即新增浪API,它傳回的資料格式為

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 == &#39;success&#39;) {
  self.message("登陆成功正在跳转,请稍候...");
  window.location.href = &#39;/&#39;;
 } 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());});
登入後複製

表單訊息,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_user
set 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(&#39;/&#39;).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及所在城市(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

更多Asp.net MVC利用knockoutjs实现登陆并记录用户的内外网IP及所在城市相关文章请关注PHP中文网!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!