欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MVC身份验证.MVC过滤器.MVC6关键字Task,Async.前端模拟表单验证,提交.自定义匿名集合.Edge导出到Excel.BootstrapTree树状菜单的全选和反选.bootstrap可搜索可多选可全选下拉框

程序员文章站 2022-07-23 09:29:52
在写这篇博客之前要唠叨几句.本人已从事开发四年有余.从前两年的热情如火.到现在的麻木.总感觉要像上突破.却又不敢轻举妄动. 没事就写点基础代码.指点下新人吧 1.MVC身份验证. 有两种方式.一个是传统的所有控制器继承自定义Control,然后再里面用MVC的过滤器拦截.所以每次网站的后台被访问时. ......

在写这篇博客之前要唠叨几句.本人已从事开发四年有余.从前两年的热情如火.到现在的麻木.总感觉要像上突破.却又不敢轻举妄动.

没事就写点基础代码.指点下新人吧

1.mvc身份验证.

   有两种方式.一个是传统的所有控制器继承自定义control,然后再里面用mvc的过滤器拦截.所以每次网站的后台被访问时.就会先走入拦截器.进行前端和后端的验证

                      一个是利用(mvc4及以上版本)自动生成的global.asax.cs中的 filterconfig.registerglobalfilters(globalfilters.filters),这个file会加载所有的过滤器.第一种方式适用目前任何版本,第二种支持mvc4以及以上,下面对两种方式一一细讲

                     1.

public class countcontroller : basecontroller

                       

            countcontroller是自定义controller,basecontroller是需要继承的control
base里两行是精华.其他自定义
public class basecontroller : controller

protected override void onactionexecuting(actionexecutingcontext filtercontext)

                          第一行是control原本继承的父类.所以目前的控制器多继承了一个父类.第二行代码就是要多继承一次的原因.onactionexecuting是每个action被调用前.不论是actionresult还是jsonresult.都会被拦截.然后我们可以拿到request.cookie和相关的请求地址.

                          就像这杨 url = $"/{filtercontext.actiondescriptor.controllerdescriptor.controllername}/{filtercontext.actiondescriptor.actionname}"; 还有这杨cookiename = request.cookies["username"].value.tostring();

                          一般cookie中会包含请求人信息.然后我们根据数据库就能检测出此人是否能访问这个前端页面或者后端接口.如果通过return true ,反之

                          

   response.redirecttoroute(new { controller = "error", action = "notfound", content = "权限不足,请联系管理员" });
                    return;

                          这杨就会跳到异常页面了.

                          如果通过了身份验证.就可以设定一个全局通用身份.httpcontext.current.user.identity.name.方便后面接口使用.但这个属性是只读的.所以要往上重写iprincipal

                          

public class myprincipal : system.security.principal.iprincipal
    {
        public myprincipal(string userid)
        {
            identity = new myidentity(userid);
        }

        public system.security.principal.iidentity identity { get; set; }

        public bool isinrole(string role)
        {
            return true;
        }
    }

    public class myidentity : system.security.principal.iidentity
    {
        public myidentity(string currentuserid)
        {
            name = currentuserid;
        }

        public bool isauthenticated
        {
            get
            {
                return true;
            }
        }

        public string name { get; }

        public string authenticationtype
        {
            get
            {
                return null;
            }
        }
    }
最后赋值的方式:
myprincipal principal = new myprincipal(username);
httpcontext.user = principal;

     2.

        (mvc4及以上版本)自动生成的global.asax.cs中的 filterconfig.registerglobalfilters(globalfilters.filters),提供三种拦截器.action,result,exption,分别是方法拦截.结果拦截.异常拦截,在fileconfig中添加三个过滤器
public class filterconfig
    {
        public static void registerglobalfilters(globalfiltercollection filters)
        {
            //filters.add(new handleerrorattribute());
            filters.add(new actionfillters());
            filters.add(new exceptionfillters());
            filters.add(new resultfillters());
            
        }
    }

                为了方便我将三个过滤器写在一个类中

        

namespace mvcapplication2.app_start
{
    public class actionfillters : filterattribute, iactionfilter
    {
        public void onactionexecuted(actionexecutedcontext filtercontext)
        {
            //执行action后执行这个方法 比如做操作日志  
        }
        public void onactionexecuting(actionexecutingcontext filtercontext)
        {
            //执行action前执行这个方法,比如做身份验证  
        }
    }
    public class exceptionfillters : filterattribute, iexceptionfilter
    {
        //发生异常时会执行这段代码
        public void onexception(exceptioncontext filtercontext)
        {
            //在这里你可以记录发生异常时你要干什么,比例写日志

            //这一行告诉系统,这个异常已经处理了,不用再处理
            filtercontext.exceptionhandled = true;
        }
    }
    public class resultfillters : filterattribute, iresultfilter
    {
        public void onresultexecuted(resultexecutedcontext filtercontext)
        {
            //执行完action后跳转后执行
        }

        public void onresultexecuting(resultexecutingcontext filtercontext)
        {
            //执行完action后跳转前执行
        }
    }

}

           接下来介绍mvc6新关键字.task,async(异步).对线程进行了封装.变成了属性.简单举个例子

using system;
using system.threading;
using system.threading.tasks;

namespace consoleapp1
{
    class program
    {
        static void main(string[] args)
        {
            new task(startcode, 2).start();
            console.writeline("主线程运行到此");
            thread.sleep(1000);

            task<int32> t = new task<int32>(n => sum((int32)n), 100);
            t.start();
            t.wait();
            console.writeline("the sum is:" + t.result);

        }
        private static void startcode(object i)
        {
            console.writeline("开始执行子线程...{0}", i);
            thread.sleep(1000);//模拟代码操作   
        }
        private static int32 sum(int32 i)
        {
            int32 sum = i;
           
            return sum-1;
        }
    }
}

   在这段代码中.task是单独启动了一个子线程运行方法.和主线程互不干涉.但是有一点task接受到的返回值要加上result.不然返回的是整个线程属性

 

接下来讲下task和mvc6的结合
 public async task<jsonresult> test()
        {
            var jsonresult = await data();
            return json(jsonresult);

        }
        private task<string> data()
        {
            return task.fromresult("hello");
        }

根据约定async 和await 永远是成双成对

async代表异步 task代表线程

接受时 用await

返回值用 task.fromresult封装

 

好吧。真的很简单的新属性

 

前端模拟表单验证.

    大家都用过mvc的表单吧.大致是view模型绑定.from 中submit 提交. controll同名同参方法接受

    但是在实际运用中略限僵硬.如果一个实体类要多次提交呢?mvc默认以实体类的名字作为控件id,一个页面出现两个同名控件只会拿到第一个的值.所以需要自定义部分表单提交.那么从头讲起吧

    

    引入以下文件

   

<link rel="stylesheet" href="~/scripts/bootstrapvalidator.css" />
<script src="~/scripts/bootstrapvalidator.js"></script>

 

 

    html表单 <form id="formeditapp" method="post" action=""> html控件在表单中实际取的name <input class="form-control" id="editappsysid" type="text" name="editappsysid" readonly="readonly">

    在jquery中

    

   $("#formeditapp").bootstrapvalidator({
            live: 'enabled',//验证时机,enabled是内容有变化就验证(默认),disabled和submitted是提交再验证
            message: '通用的验证失败消息',
            feedbackicons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                editappaccount: {
                    validators: {
                        notempty: {
                            message: '通道账号必填'
                        }
                    }
                },
                editapppassword: {
                    validators: {
                        notempty: {
                            message: '通道密码必填'
                        }
                    }
                },

            }
        });

    当没有通过验证的时候

  MVC身份验证.MVC过滤器.MVC6关键字Task,Async.前端模拟表单验证,提交.自定义匿名集合.Edge导出到Excel.BootstrapTree树状菜单的全选和反选.bootstrap可搜索可多选可全选下拉框

 

    表单的提交按钮

   $("#editappsubmit").click(function () {
            $("#formeditapp").bootstrapvalidator('validate');//提交验证
            if ($("#formeditapp").data('bootstrapvalidator').isvalid()) {//获取验证结果,如果成功,执行下面代码
                $("#formeditapp").data('bootstrapvalidator').resetform();
                var array = new object();
                array.sysid = $("#editappsysid").val();
                array.account = $("#editappaccount").val();
                array.password = $("#editapppassword").val();
                array.appenable = $("#editappenable option:selected").val();
                array.appchannel = $("#editappchannel option:selected").val();

               数组的值和服务端实体类对应,ajax 设置参数如下

             

     $.ajax({
                    url: '/business/updatesystemsms',
                    type: "post",
                    data: json.stringify(array),
                    contenttype: "application/json; charset=utf-8",

 

          服务端设置参数如下

    

updatesystemsms([system.web.http.frombody]msgsysappconfigentity sysconfig)

        这杨就完成了

        自定义匿名集合

          很多时候我们不想写实体类.如何偷懒呢

         

     

    var tracklist = new[]{ new  {
                    id = string.empty,
                        channelkey=string.empty,
                        tomobilstatus=0,
                        createtime = string.empty,
                        type=string.empty
                              }}.tolist();
            tracklist.clear();

 

     这杨数组中new匿名集合.类型是list<a> {string xxx,,string xx1.....}

     如果是非对应数据库实体.用这个方式.快感略强烈

     

   edge导出到excel 
在win10中推出了edge替换ie,但是edge的内核信息和ie完全不一致.所以需要更新edge导出excel的功能.至于ie,google等其他浏览器利用table导出excel可以参考之前的博客

 function edgetoexcel(obj) {
            var ohtml = document.getelementsbyclassname(obj)[0].outerhtml;
            var excelhtml = `
    <html>
    <head>
    <meta charset='utf-8' />
    </head>
    <body>
    ${ohtml}
    </body>
    </html>
    `;

            var excelblob = new blob([excelhtml], { type: 'application/vnd.ms-excel' })
            // 创建一个a标签
            var oa = document.createelement('a');
            // 利用url.createobjecturl()方法为a元素生成blob url
            oa.href = url.createobjecturl(excelblob);
            // 给文件命名
            oa.download = '下载.xls';
            // 模拟点击
            oa.click();
            // 移除
            oa.remove();
        }
     如何区分edge呢
      function getexplorer() {
            var useragent = navigator.useragent; //取得浏览器的useragent字符串
            var isie = useragent.indexof("compatible") > -1 && useragent.indexof("msie") > -1; //判断是否ie<11浏览器
            var isedge = useragent.indexof("edge") > -1 && !isie; //判断是否ie的edge浏览器
                 if (isedge) {
                     return 'edge';
                }
            else if (useragent.indexof("chrome") >= 0) {
                return 'chrome';
            }
        }

       大家要注意win7 的ie 9,10,11

       和win10 ie 9,10,11内核信息完全不一致

       edge和ie的内核信息也不一致.所以在做兼容性的时候要多考虑一下

 

       树状菜单的全选和反选.如果没有这两个功能.一个一个点也是非常反人类的

      

 var nodecheckedsilent = false;
        function nodechecked(event, node) {
            if (nodecheckedsilent) {
                return;
            }
            nodecheckedsilent = true;
            checkallparent(node);
            checkallson(node);
            nodecheckedsilent = false;
        }

        var nodeuncheckedsilent = false;
        function nodeunchecked(event, node) {
            if (nodeuncheckedsilent)
                return;
            nodeuncheckedsilent = true;
            uncheckallparent(node);
            uncheckallson(node);
            nodeuncheckedsilent = false;
        }

        //选中全部父节点
        function checkallparent(node) {
            $('#tree').treeview('checknode', node.nodeid, { silent: true });
            var parentnode = $('#tree').treeview('getparent', node.nodeid);
            if (!("nodeid" in parentnode)) {
                return;
            } else {
                checkallparent(parentnode);
            }
        }

        //取消全部父节点
        function uncheckallparent(node) {
            $('#tree').treeview('unchecknode', node.nodeid, { silent: true });
            var siblings = $('#tree').treeview('getsiblings', node.nodeid);
            var parentnode = $('#tree').treeview('getparent', node.nodeid);
            if (!("nodeid" in parentnode)) {
                return;
            }
            var isallunchecked = true;  //是否全部没选中
            for (var i in siblings) {
                if (siblings[i].state.checked) {
                    isallunchecked = false;
                    break;
                }
            }
            if (isallunchecked) {
                uncheckallparent(parentnode);
            }

        }

        //级联选中所有子节点
        function checkallson(node) {
            $('#tree').treeview('checknode', node.nodeid, { silent: true });
            if (node.nodes != null && node.nodes.length > 0) {
                for (var i in node.nodes) {
                    checkallson(node.nodes[i]);
                }
            }
        }

        //级联取消所有子节点
        function uncheckallson(node) {
            $('#tree').treeview('unchecknode', node.nodeid, { silent: true });
            if (node.nodes != null && node.nodes.length > 0) {
                for (var i in node.nodes) {
                    uncheckallson(node.nodes[i]);
                }
            }
        }

 

       如何使用呢

   

   $('#tree').treeview({
                                data: data,
                                showcheckbox: true,
                                onnodechecked: nodechecked,
                                onnodeunchecked: nodeunchecked
                            });

     已经集成的相当好啦.用的时候注意一下控件id

 

 今天刚折腾了一个bootstrap可搜索下拉框.就顺带讲一下吧

    <script src="~/scripts/bootstrap/bootstrap-select.js" defer></script>
    <link rel="stylesheet" href="~/content/bootstrap/bootstrap-select.css">

    

  <select class="form-control selectpicker show-tick" data-live-search="true" id="fromsys" name="fromsys" data-live-search="true" multiple data-actions-box="true">
                     
                                <option value="@item.value">@item.text</option>
                  
                    </select>

 

selectpicker show-tick 样式是可搜索下拉框必备的样式
data-live-search="true" 允许搜索 
 
multiple 下拉框允许多选

data-actions-box="true" 下拉框允许全选

MVC身份验证.MVC过滤器.MVC6关键字Task,Async.前端模拟表单验证,提交.自定义匿名集合.Edge导出到Excel.BootstrapTree树状菜单的全选和反选.bootstrap可搜索可多选可全选下拉框