C# 从登陆开始 MVC4+BOOTSTRAP

2019-01

1.web登陆

基于bootstrap 开发一个注册及登陆页面。后端调用webapi实现

icheck 选择框控件

jquery.validate 进行表单字段认证,参考网站

http://www.runoob.com/jquery/jquery-plugin-validate.html

$.extend($.validator.messages, {
    required: "这是必填字段",
    remote: "请修正此字段",
    email: "请输入有效的电子邮件地址",
    url: "请输入有效的网址",
    date: "请输入有效的日期",
    dateISO: "请输入有效的日期 (YYYY-MM-DD)",
    number: "请输入有效的数字",
    digits: "只能输入数字",
    creditcard: "请输入有效的信用卡号码",
    equalTo: "你的输入不相同",
    extension: "请输入有效的后缀",
    maxlength: $.validator.format("最多可以输入 {0} 个字符"),
    minlength: $.validator.format("最少要输入 {0} 个字符"),
    rangelength: $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"),
    range: $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"),
    max: $.validator.format("请输入不大于 {0} 的数值"),
    min: $.validator.format("请输入不小于 {0} 的数值")
});

示例代码:MVC 模板页引用的css及js文件

 
    
 public static void RegisterBundles(BundleCollection bundles)
        {
            //jquery 3.3.1
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));                   
            //jquery validate
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate.js"));
            //vue 2.x
            bundles.Add(new ScriptBundle("~/bundles/vue").Include(
                     "~/Scripts/vue/vue.js"));
            //bootstrap 3.3.7
            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                    "~/Scripts/bootstrap/bootstrap.js"));           //获取浏览器信息 modernizr
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));//bootstrap及global 全局 css
            bundles.Add(new StyleBundle("~/Content/themes/bootstrap/css").Include(
                "~/Content/themes/bootstrap/bootstrap-theme.css",
                "~/Content/themes/bootstrap/bootstrap.css",
                "~/Content/global.css"));

        }
 
    

 

 

 登陆页代码:引用模板页 _LayoutAccount.cshtml

模板页代码:

DOCTYPE html>

<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>@ViewBag.Titletitle>
    @Styles.Render("~/Content/themes/bootstrap/css")
    @Scripts.Render("~/bundles/modernizr", "~/bundles/jquery", "~/bundles/bootstrap", "~/bundles/jqueryval")
    <link rel="stylesheet" href="/plugins/iCheck/all.css">
    <script src="/plugins/iCheck/icheck.js">script>
head>
<body class="hold-transition login-page login-register">
    @RenderBody()
body>
html>

 

@{

    ViewBag.Title = "登陆";
    Layout = "~/Views/Shared/_LayoutAccount.cshtml";
}
<div class="login-box">
    <div class="login-logo">
        登陆
    div>
    <div class="login-box-body">
        <p class="login-box-msg">p>
        <form class="loginfrom">
            <div class="form-group has-feedback">
                <input type="text" class="form-control account" name="account" placeholder="登录名">
                <span class="glyphicon glyphicon-user form-control-feedback">span>
            div>
            <div class="form-group has-feedback">
                <input type="password" class="form-control password" name="password" placeholder="密码">
                <span class="glyphicon glyphicon-lock form-control-feedback">span>
            div>
            <div class="row">
                <div class="col-xs-6">
                    <div class="checkbox icheck">
                        <label class="mycheck">
                        label>
                    div>
                div>
                <div class="col-xs-6">
                    <button type="submit" class="btn btn-primary btn-block btn-flat">登陆button>
                div>
            div>
        form>
        <div class="row">
            <div class="col-xs-6"><a href="#">忘记密码?a>div>
            <div class="col-xs-6 text-right"><a href="register" class="text-center">现在注册a>div>
        div>
    div>
div>
<script>
    $(function () {
        //加载checkbox
        $(".mycheck").append("  记住密码");
        $('input').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass: 'iradio_minimal-blue',
            increaseArea: '15%' // optional
        });
        //validate.js
        $(".loginfrom").validate(
                {
                    debug: true, //调试模式取消submit的默认提交功能
                    //errorClass: "label.error", //默认为错误的样式类为:error
                    focusInvalid: true, //当为false时,验证无效时,没有焦点响应
                    onkeyup: false,
                    submitHandler: function (form) {   //表单提交句柄,为一回调函数,带一个参数:form
                        //alert("验证通过,可以登陆");
                        /*提交数据*/
                      var formData = new FormData();                
                        var account = $(".account").val();
                        var password = $(".password").val();//加密
                        formData.append("account",account);
                        formData.append("password", password);
                        $.ajax({
                            type: 'post',
                            url: "Login",
                            // 告诉jQuery不要去处理发送的数据
                            processData: false,
                            // 告诉jQuery不要去设置Content-Type请求头
                            contentType: false,
                            data: formData,
                            success: function (responsedata) {
                                if (responsedata.Status == 1) {
                                    console.log("成功" + responsedata.ResultMessage);
                                } else {
                                    console.log("失败");
                                }
                            }
                        });
                    },
                    //校验
                    rules: {
                        account: {
                            required: true
                        },
                        password: { required: true },
                        recheck: { required: false }
                    },
                    //错误信息
                    messages: {
                        account: {
                            required: "请输入账号"
                        },
                        password: {
                            required: "请输入密码"
                        }
                    },
                    showErrors: function (errorMap, errors) {
                        if (errors.length < 1) {
                            this.toHide.parent().remove();//如果没有错误,删除错误信息元素(此处为显示的error的parent节点需要隐藏),否则 defaultShowErrors会显示所有错误
                        }
                        this.defaultShowErrors(); //控件默认错误显示方式
                    },
                    errorElement: "div",  //错误信息容器类型:label,em,span,div eg...
                    // wrapper: "div", //错误信息容器类型外围再包一层
                    errorPlacement:  //自定义错误样式,来源于defaultShowErrors 中的showLabel()
                        function (error, element) {
                            //如果没有错误信息,则不进行插入(对于引用errorClass中自定义的css可以避免重复插入样式的BUG)
                            if (error[0].outerText == "") {
                                return;
                            }
                            //模拟boostrap popover 的样式
                            var left = 20;
                            left += element[0].offsetWidth;
                            var width = 10;
                            width = error[0].outerHTML.length * 2;
                            var height = 'auto';
                            //拼接错误信息主体
                            var popo = "
" + error[0].outerHTML + "
"; //修改错误显示位置 if (element[0].type == "checkbox") { element.parent().parent().append(popo);//如果是 checkbox 则 插入父节点+2元素的内部的后面,因为使用了icheck,会多一层 } else { element.parent().append(popo);//其他元素插入父节点最后 } }, //验证成功后 success: function (element) { element.parent().remove();//验证成功,移除整个element对象 } } ); }); script>

页面效果:

C# 从登陆开始 MVC4+BOOTSTRAP_第1张图片

 

 

注册页面:

@{
    ViewBag.Title = "用户注册";
    Layout = "~/Views/Shared/_LayoutAccount.cshtml";
}
<div class="register-box">
    <div class="login-logo">
        用户注册
    div>
    <div class="register-box-body">
        <p class="register-box-msg">p>
        <form class="registerform">
            <div class="form-group has-feedback">
                <input type="text" class="form-control" name="account" placeholder="登录名">
                <span class="glyphicon glyphicon-user form-control-feedback">span>
            div>
            <div class="form-group has-feedback">
                <input type="email" class="form-control " name="email" placeholder="邮箱">
                <span class="glyphicon glyphicon-envelope form-control-feedback">span>
            div>
            <div class="form-group has-feedback">
                <input type="text" class="form-control " name="realname" placeholder="真实姓名">
                <span class="glyphicon glyphicon-registration-mark form-control-feedback">span>
            div>
            <div class="form-group has-feedback">
                <input type="number" class="form-control " name="tel" min="0" placeholder="电话">
                <span class="glyphicon glyphicon-phone form-control-feedback">span>
            div>
            <div class="form-group has-feedback">
                <input type="password" class="form-control " name="password" id="password" placeholder="密码">
                <span class="glyphicon glyphicon-lock form-control-feedback">span>
            div>
            <div class="form-group has-feedback">
                <input type="password" class="form-control  " name="confirm_password" placeholder="确认密码">
                <span class="glyphicon glyphicon-record form-control-feedback">span>
            div>
            <div class="row">
                <div class="col-sm-8">
                    <div class="checkbox icheck">
                        <label class="iprover">
                            我已阅读,且同意 <a data-toggle="modal" data-target="#myModal">协议a>
                        label>
                    div>
                div>
                <div class="col-sm-4">
                    <button type="submit" class="btn btn-primary btn-block btn-flat">注册button>
                div>
            div>
        form>
        <div class="row">
            <div class="col-md-6">          
            div>
            <div class="col-md-6 text-right">div>
        div>
    div>
    
    <div class="modal fade modal-primary" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×span>button>
                    <h4 class="modal-title">用户协议h4>
                div>
                <div class="modal-body">
                    <p>我是协议,请阅读p>
                div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline " data-dismiss="modal">关闭button>
                div>
            div>
        div>
    div>
div>
<script>
    $(function () {
        //加载checkbox,使用icheck
        $(".iprover").prepend("");//插入元素内部的前面
        $('input').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass: 'iradio_minimal-blue',
            increaseArea: '15%' // optional
        });     
        //validate
        $(".registerform").validate(
               {
                   debug: true, //调试模式取消submit的默认提交功能
                   //errorClass: "label.error", //默认为错误的样式类为:error
                   focusInvalid: false, //当为false时,验证无效时,没有焦点响应
                   onkeyup: false,
                   submitHandler: function (form) {   //表单提交句柄,为一回调函数,带一个参数:form
                       alert("可以提交表单");
                       form.submit();   //提交表单
                   },
                   rules: {
                       account: { required: true },
                       email: { required: true, email: true }, //accept上传后文件后缀名
                       realname: { required: true },
                       tel: { range: [10000000000, 20000000000] },
                       password: { required: true, minlength: 6 },
                       confirm_password: { required: true, equalTo: "#password", minlength: 6 },
                       proverd: { required: true }
                   },
                   messages: {
                       account: {
                           required: "请输入账号"
                       },
                       password: {
                           required: "请输入密码",
                           minlength: "密码长度错误,最小6位"
                       },
                       realname: {
                           required: "请输入真实姓名"
                       },
                       tel: {
                           range: "请输入正确手机号码"
                       },
                       email: {
                           required: "请输入邮箱",
                           email: "请填写正确的邮箱信息"
                       },
                       confirm_password: {
                           required: "请输入确认密码",
                           equalTo: "两次输入密码不一致,请重新输入",
                           minlength: "密码长度错误,最小6位"
                       },
                       proverd: {
                           required: "请确认用户协议"
                       }
                   },
                   showErrors: function (errorMap, errors) {

                       if (errors.length < 1) {
                           this.toHide.parent().remove();//如果没有错误,删除错误信息元素(此处为显示的error的parent节点需要隐藏)
                       }
                       /*废弃*/                          
                       /*else {
                           for (var el in errors) {
                               //errors[el].element.parent().show();
                               //this.toHide.parent().show()
                               this.toHide[1].parentElement.style.display = 'block'
                           }
                        this.toHide.parent().show();//如果有错误,显示弹出框(此处为显示的error的parent节点需要显示)
                       }*/

                       this.defaultShowErrors(); //控件默认错误显示方式
                   },
                   errorElement: "div",  //错误信息容器类型:label,em,span,div eg...
                   // wrapper: "div", //错误信息容器类型外围再包一层
                   errorClass: "validatecss", //错误信息css样式名称      glyphicon glyphicon-warning-sign
                   errorPlacement:  //自定义错误样式,来源于defaultShowErrors 中的showLabel()
                       function (error, element) {
                           //$('[data-toggle="popover"]').popover(); //激活弹出框

                           //如果没有错误信息,则不进行插入(对于引用errorClass中自定义的css可以避免重复插入样式的BUG)
                           if (error[0].outerText == "") {
                               return;
                           }
                           //模拟boostrap popover 的样式
                           var left = 20;
                           left += element[0].offsetWidth;
                           var width = 10;
                           width = error[0].outerHTML.length * 2;
                           var height = 'auto';                          
                           //拼接错误信息
                           var popo = "
" + error[0].outerHTML + "
"; //修改错误显示位置 if (element[0].type == "checkbox") { element.parent().parent().append(popo);//如果是 checkbox 则 插入父节点+2元素的内部的后面,因为使用了icheck,会多一层 } else { element.parent().append(popo);//其他元素插入父节点最后 } /*废弃 //错误信息自定义css error.attr({ style: "position:absolute; top:10px; left:" + element[0].offsetWidth + "px; width:" + error[0].offsetWidth + "px; display:block" }); //修改错误显示位置 另外一种形式(bootstrap 弹出框),有缺陷,不好 element.popover({ placement: "right", //top left right bottom content: function () { return error[0].outerText }, title: "错误信息", template: "", trigger: "focus" }); element.popover("show"); */ }, //验证成功后 success: function (element) { element.parent().remove();//验证成功,移除整个element对象 } /*弃用 //如果失去焦点,且没有错误,则移除错误信息 onfocusout:function(element,error) { } */ /*弃用 //异步验证 remote: { url: "", //后台处理程序 type: "post", //数据发送方式 dataType: "json", //接受数据格式 data: { //要传递的数据 username: function () { // return $("#username").val(); //远程地址只能输出 "true" 或 "false",不能有其他输出。 } } } */ } ); }); script> <style> .validatecss { /*font-family: 'Glyphicons Halflings';*/ } style>

效果:

C# 从登陆开始 MVC4+BOOTSTRAP_第2张图片

 

 

 

2.加密

 利用对称及非对称加密进行数据加密

3.认证

Forms

 

4.退出

 

5.其他

AD 认证代码段:

string m_address = ConfigHelper.ReadConfig("ADaddress");
using
(DirectoryEntry entry = new DirectoryEntry(m_address, UserName, Password, AuthenticationTypes.Secure))//获取ad信息 { DirectorySearcher Searcher = new DirectorySearcher(entry);//查询对象 Searcher.Filter = (string.Format("(&(objectClass=user)(sAMAccountName={0}))", UserName));//根据username获取ad账号信息 SearchResultCollection Collections = Searcher.FindAll(); if (Collections.Count == 1) { return true; } else { return false; } }

FormsAuthentication  : Web 应用程序管理 Forms 身份验证服务

FormsAuthentication.SignOut();

转载于:https://www.cnblogs.com/daniel-niu/p/10270845.html

你可能感兴趣的:(C# 从登陆开始 MVC4+BOOTSTRAP)