ASP. NET MVC uses Knockoutjs to log in and record users ' internal and external IP and city

Source: Internet
Author: User
This article mainly introduces the ASP. NET MVC uses Knockoutjs to realize landing and record the user's internal and external network IP and the city (recommended), the need for friends can refer to the next

Objective

The first article in front opened, now want to start from the landing, but there are still a lot of things to be written in front, such as

1. Route configuration for MVC and Web APIs, how the route configuration of the Web API supports namespaces

2, How to configure filters (security verification, error handling, etc.)

3, custom filters, Httprouteconstraint, Modelbinder and httpparameterbinding, etc.

These problems have been encountered in my development process, but I feel that I have to say too much at every point. If there is a need, then go back and write.

Demand

Still the same, we must first understand the landing to achieve what:

1. Landing page (user name, password, remember me, login button, reset button)

2, the message display (such as error display such as error, log on when the login, login successful display is jumping, etc.)

3. Login processing (verify, login, login disabled form, update user login times and time, add login history) including the user's intranet IP network IP is also located in the city, other business processing)

4. Successful Jump

Achieve results

Let's take a look at the implementation before we do it.

Landing page

Jump page

Login History

Requirements analysis and implementation

Requirements are basically good to achieve, only log in to record the internal and external network IP and city to consider. in ASP. NET to get clients inside and outside the network IP is still more trouble, and to get the city is basically impossible, so we have to consider the use of third-party API to achieve.

1, intranet IP directly in the background to take

2, the network IP can be obtained through the Sina API HTTP://COUNTER.SINA.COM.CN/IP, the original can also return to the city, backstage do not know what reason, can only return IP

3, the city through the Baidu API Http://api.map.baidu.com/location/ip?ak=&ip to obtain, but this will not return to the external network IP so I just two together, pretty egg hurts.

The above in the client to access the corresponding API and there is a cross-domain problem, through the survey found that Baidu API support JSONP, can be a good solution to cross-domain problems, Sina API does not support but it returns a variable, we can directly write the Sina API in the page srcipt to get the corresponding variable.

Technology should be all right, so let's start writing.

Specific implementation

First step: Create a new Logincontroller in MVC and add the following code

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 = "Building Materials management system"; Viewbag.enname = "Engineering Material mangange System"; return View (); } }}

Classes are decorated with the AllowAnonymous property to ensure that they are not logged in and accessible.

The second step: add the corresponding view, add ~/views/login/index.cshtml, the code is as follows

@{viewbag.title = "Login System"; Layout = null;} <!doctype html>

1, the last of the script is to add Sina API to get the extranet IP information, it returns the data format for

var ildata = new Array ("117.30.94.103", "Reserved Address", "", "", ""); if (typeof (Ildata_callback)! = "undefined") {Ildata_callback ();}

It actually has a callback function, similar to JSONP, but the function name is fixed and no data is passed. We have direct access to ildata[0] to get the extranet IP.

2. data-bind= "" In HTML above is written as Knouckoutjs for binding to ViewModel properties

Step Three: Create ViewModel

var ViewModel = function () {var = this; This.form = {usercode:ko.observable (), password:ko.observable (), Remembe R: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 (" login success is jumping, please wait.  ."); 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 ("Login processing, please wait ...");}, 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 ());});

Defines ViewModel, whose properties include from form information, message hint information, Loginclick login, ResetClick reset. The init part can actually not be put into the viewmodel.

1, $.getjson is the JSONP access, which adds the parameter callback=?,jquery automatically processed into the current callback function, that is, cross-domain success will automatically callback the current function and incoming data. We use form.city in ViewModel to receive city information from the requested data.

2, the last sentence ko.applybindings (new ViewModel ()) is the implementation of the page and ViewModel binding, at this point, the front desk is complete. Next write login processing doAction, or put in Logincontroller, access address is/login/doaction.

Fourth step: Add the Doaction method to the Logincontroller to return the JSON data. The code is as follows:

Public Jsonresult DoAction (Jobject request) {var message = new Sys_userservice (). Login (Request); return Json (message, jsonrequestbehavior.denyget);}

And then process it in the service layer

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"); User name password Check if (string.isnullorempty (usercode) | | String.IsNullOrEmpty (Password)) return new {status = "error", message = "User name or password cannot be empty!" " }; User name password verification 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 = "username or password is incorrect!" " }; Call the login mechanism in the framework var Loginer = new Loginerbase {Usercode = result. Usercode, UserName = result. UserName}; Formsauth.signin (Loginer.  Usercode, Loginer, 60 * 8); At the back of the landingManagement. Updateuserlogincountanddate (Usercode); Update user login times and time this. Appendloginhistory (Request); Add Login resume Mmsservice.loginhandler (request); Other business processing of MMS System//Return login successful return new {status = "Success", message = "Login Successful!" " }; } Update user login times and time public void Updateuserlogincountanddate (string usercode) {db. SQL (@ "update sys_userset logincount = IsNull (logincount,0) + 1, lastlogindate = getdate () where usercode = @0", Usercode) . Execute (); }//Add login Resume public void Appendloginhistory (Jobject request) {var lanip = Zhttp.clientip; var hostName = Zhttp.islanip (LanI P)? ZHttp.ClientHostName:string. Empty; If the intranet is acquired, otherwise the error can not be obtained, and the impact of efficiency 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 (); } }}

The receive parameter is defined as the Jobject object is convenient to obtain the request data, the data service Getmodel is the service base class existing method, this uses two functions, one for updateuserlogincountanddate to update the user login times and the time processing, Another appendloginhistory adds a login resume. This is done!

Described above is a small part of the introduction of ASP. NET MVC using KNOCKOUTJS to achieve landing and record the user's internal and external network IP and the city (recommended), I hope to help you, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for your support for topic.alibabacloud.com!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.