使用HttpContext的User属性来实现用户身份验证

使用HttpContext中的User属性来实现用户身份验证之用户验证票篇 在我的上一篇《使用HttpContext中的User属性来实现用户身份验证》中已经讲了怎样来使用HttpContext.User属性来实现用户身份验证,并且还写了一个示例程序。但是,在上一篇文章中,我们使用的是系统缓存来保存用户的登录信息,这无疑是占用系统资源的一种做法,那有没有更好的办法呢?我在上一章中说过大家可以尝试使用用户验证票的方式来保存用户登录信息的,这种方式是基于Cookie原理来实现 阅读详情

HttpContext类包含了个别HTTP请求的所有特定HTTP信息。这个示例主要是讲如何使用HttpContext类中的User属性来实现用户验证!
用户验证是大部分ASP.NET WEB应用程序都要用到的,它在整个应用程序中占有很重要的地位,在.NET中,包含了很多种用户验证方式,如众所周知的PassPort认证,Windows认证,Form认证等等,可是这些都很难满足我们在实际应用中的需求,以致于很多朋友都是自己另外写代码来实现自己需要的功能,这让我们在安全性以及系统效率上要考虑很多。
实际上,ASP.NET中内置的用户验证机制功能非常强大,同时也具有非常好的的可扩展性,它能够在HttpContext对象中生成一个名为User的属性,这个属性能让我们访问各种信息,包括用户是否已验证,用户的类型,用户名等等,我们还可以对该属性的功能进性扩展,以实现我们的要求。
分配给HttpContext.User的对象必须实现IPrincipal接口,而Iprincipal定义的属性之一是Identity,它必须实现Iidentity接口。因为,我们只要写了实现这两个接口的类,就可以在这些类中添加任何我们所需要的功能。
首先,我们创建两个实现Iprincipal和Iidentity的类,分别为MyIprincipal和MyIdentity

MyIprincipal.cs

using System;
using System.Collections;

namespace HttpContextUserEG
{
    /// <summary>
    /// MyPrincipal 的摘要说明。
    /// </summary>
    /// 实现IPrincipal接口
    public class MyPrincipal : System.Security.Principal.IPrincipal
    {
       private System.Security.Principal.IIdentity identity;
       private ArrayList roleList;

       public MyPrincipal(string userID,string password)
       {
          //
          // TODO: 在此处添加构造函数逻辑
          //
          identity = new MyIdentity(userID,password);
          if(identity.IsAuthenticated)
          {
             //如果通过验证则获取该用户的Role,这里可以修改为从数据库中
             //读取指定用户的Role并将其添加到Role中,本例中直接为用户添加一个Admin角色
             roleList = new ArrayList();
             roleList.Add("Admin");
          }
          else
          {
             // do nothing
          }
       }

       public ArrayList RoleList
       {
          get
          {
             return roleList;
          }
       }
       #region IPrincipal 成员

       public System.Security.Principal.IIdentity Identity
       {
          get
          {
             // TODO:   添加 MyPrincipal.Identity getter 实现
             return identity;
          }
          set
          {
             identity = value;
          }
       }

       public bool IsInRole(string role)
       {
          // TODO:   添加 MyPrincipal.IsInRole 实现
          return roleList.Contains(role);;
       }

       #endregion
    }
}


MyIdentity.cs

using System;

namespace HttpContextUserEG
{
    /// <summary>
    /// MyIdentity 的摘要说明。
    /// </summary>
    /// 实现IIdentity接口
    public class MyIdentity : System.Security.Principal.IIdentity
    {
       private string userID;
       private string password;

       public MyIdentity(string currentUserID,string currentPassword)
       {
          //
          // TODO: 在此处添加构造函数逻辑
          //
          userID = currentUserID;
          password = currentPassword;
       }

       private bool CanPass()
       {
          //这里朋友们可以根据自己的需要改为从数据库中验证用户名和密码,
          //这里为了方便我直接指定的字符串
          if(userID == "yan0lovesha" && password == "iloveshasha")
          {
             return true;
          }
          else
          {
             return false;
          }
       }

       public string Password
       {
          get
          {
             return password;
          }
          set
          {
             password = value;
          }
       }

       #region IIdentity 成员

       public bool IsAuthenticated
       {
          get
          {
             // TODO:   添加 MyIdentity.IsAuthenticated getter 实现
             return CanPass();
          }
       }

       public string Name
       {
          get
          {
             // TODO:   添加 MyIdentity.Name getter 实现
             return userID;
          }
       }

       //这个属性我们可以根据自己的需要来灵活使用,在本例中没有用到它
       public string AuthenticationType
       {
          get
          {
             // TODO:   添加 MyIdentity.AuthenticationType getter 实现
             return null;
          }
       }

       #endregion
    }
}

在完成了这两个类之后我们还要创建一个自己的Page类,来配合我们的验证,这里我们将其命名为MyPage,继承自Page类

MyPage.cs

using System;
using System.Collections;

namespace HttpContextUserEG
{
    /// <summary>
    /// MyPage 的摘要说明。
    /// </summary>
    /// 继承自Page类
    public class MyPage : System.Web.UI.Page
    {
       public MyPage()
       {
          //
          // TODO: 在此处添加构造函数逻辑
          //
       }

       protected override void OnInit(EventArgs e)
       {
          base.OnInit (e);
          this.Load +=new EventHandler(MyPage_Load);
       }

       //在页面加载的时候从缓存中提取用户信息
       private void MyPage_Load(object sender, System.EventArgs e)
       {
          if(Context.User.Identity.IsAuthenticated)
          {
             if(Context.Cache["UserMessage"] != null)
             {
                Hashtable userMessage = (Hashtable)Context.Cache["UserMessage"];
                MyPrincipal principal = new MyPrincipal(userMessage["UserID"].ToString(),userMessage["UserPassword"].ToString());
                Context.User = principal;
             }
          }
       }
    }
}

下面就是我们的界面WebForm.aspx和WebForm.aspx.cs

WebForm.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="HttpContextUserEG.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    <HEAD>
       <title>WebForm1</title>
       <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
       <meta content="C#" name="CODE_LANGUAGE">
       <meta content="JavaScript" name="vs_defaultClientScript">
       <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
    </HEAD>
    <body>
       <form id="Form1" method="post" runat="server">
          <P><FONT face="宋体">用户名:
                <asp:TextBox id="tbxUserID" runat="server"></asp:TextBox><BR>
                密 码:
                <asp:TextBox id="tbxPassword" runat="server" TextMode="Password"></asp:TextBox></FONT></P>
          <P><FONT face="宋体">
                <asp:Button id="btnLogin" runat="server" Text="登录"></asp:Button>
                <asp:Label id="lblLoginMessage" runat="server"></asp:Label></FONT></P>
          <P><FONT face="宋体">
                <asp:Panel id="Panel1" runat="server" Visible="False">
                   <P>
                      <asp:Button id="btnAdmin" runat="server" Text="角色1"></asp:Button>
                      <asp:Button id="btnUser" runat="server" Text="角色2"></asp:Button></P>
                   <P>
                      <asp:Label id="lblRoleMessage" runat="server"></asp:Label></P>
                </asp:Panel>
                <P></P>
             </FONT>
       </form>
    </body>
</HTML>

WebForm1.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace HttpContextUserEG
{
    /// <summary>
    /// WebForm1 的摘要说明。
    /// </summary>
    /// 将这里本来继承自Page类改为继承自我们自己的MyPage类
    public class WebForm1 : HttpContextUserEG.MyPage
    {
       protected System.Web.UI.WebControls.TextBox tbxUserID;
       protected System.Web.UI.WebControls.TextBox tbxPassword;
       protected System.Web.UI.WebControls.Panel Panel1;
       protected System.Web.UI.WebControls.Button btnAdmin;
       protected System.Web.UI.WebControls.Button btnUser;
       protected System.Web.UI.WebControls.Label lblRoleMessage;
       protected System.Web.UI.WebControls.Label lblLoginMessage;
       protected System.Web.UI.WebControls.Button btnLogin;
    
       private void Page_Load(object sender, System.EventArgs e)
       {
          // 在此处放置用户代码以初始化页面
       }

       #region Web 窗体设计器生成的代码
       override protected void OnInit(EventArgs e)
       {
          //
          // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
          //
          InitializeComponent();
          base.OnInit(e);
       }
      
       /// <summary>
       /// 设计器支持所需的方法 - 不要使用代码编辑器修改
       /// 此方法的内容。
       /// </summary>
       private void InitializeComponent()
       {    
          this.btnLogin.Click += new System.EventHandler(this.btnLogin_Click);
          this.btnAdmin.Click += new System.EventHandler(this.btnAdmin_Click);
          this.btnUser.Click += new System.EventHandler(this.btnUser_Click);
          this.Load += new System.EventHandler(this.Page_Load);

       }
       #endregion

       private void btnLogin_Click(object sender, System.EventArgs e)
       {
          MyPrincipal principal = new MyPrincipal(tbxUserID.Text,tbxPassword.Text);
          if(!principal.Identity.IsAuthenticated)
          {
             lblLoginMessage.Text = "用户名或密码不正确";
             Panel1.Visible = false;
          }
          else
          {
             // 如果用户通过验证,则将用户信息保存在缓存中,以备后用
             // 在实际中,朋友们可以尝试使用用户验证票的方式来保存用户信息,这也是.NET内置的用户处理机制
             Context.User = principal;
             Hashtable userMessage = new Hashtable();
             userMessage.Add("UserID",tbxUserID.Text);
             userMessage.Add("UserPassword",tbxPassword.Text);
             Context.Cache.Insert("UserMessage",userMessage);
             lblLoginMessage.Text = tbxUserID.Text + "已经登录";
             Panel1.Visible = true;
          }
       }

       private void btnAdmin_Click(object sender, System.EventArgs e)
       {
          // 验证用户的Role中是否包含Admin
          if(Context.User.IsInRole("Admin"))
          {
             lblRoleMessage.Text = "用户" + ((MyPrincipal)Context.User).Identity.Name + "属于Admin组";
          }
          else
          {
             lblRoleMessage.Text = "用户" + Context.User.Identity.Name + "不属于Admin组";
          }
       }

       private void btnUser_Click(object sender, System.EventArgs e)
       {
          // 验证用户的Role中是否包含User
          if(Context.User.IsInRole("User"))
          {
             lblRoleMessage.Text = "用户" + Context.User.Identity.Name + "属于User组";
          }
          else
          {
             lblRoleMessage.Text = "用户" + Context.User.Identity.Name + "不属于User组";
          }
       }
    }
}

代码部分介绍完了,朋友们可以自己试试来看到效果,在这个例子中很多地方都为了方便而直接给予赋值,在实际应用中,这些将是从数据库或从其它配置文件中得到,而这种方法的可扩展性是非常高的,我们可以根据自己的需要来扩展MyIprincipal和MyIdentity类的功能。比如我们可以添加一个IsInPermission来使用户不仅属于角色,每个角色还可以拥有不同的权限。在本例中,在用户验证过后是通过使用缓存来保存已验证用户的信息的,我们还可以尝试使用用户验证票的方式来实现。
我们可以看到,这种用户验证机制,在我们的程序越宠大,它所带来的好处就越多,而且他还有很多值得我们发掘的地方!

ASP.NET 身份验证、会话状态 持久性 Cookie 不超时。在认证阶段,ASP.NET会检查当前请求,根据web.config设置的认证方式,尝试构造HttpContext.User对象供我们在后续的处理中使用。在授权阶段,会检查当前请求所访问的资源是否允许访问,因为有些受保护的页面资源可能要求特定的用户或者用户组才能访问。mode="SqlServer" 存储在sql server中特点:工作负载会变大,但信息不会丢失 stateConnectionString :指定asp.net应用程序存储远程会话状态的服务器名,默认为本机。 阅读详情

相关推荐

ASP.NET自定义身份验证的实践

事情是这样的:有一套ASP.NET应用程序,用户一般会用工号登录,但是我们希望在应用程序中方便地访问到该用户相关的其他信息,例如用户名或者工厂名称。 按照标准的ASP.NET Membership的做法,它不能提供这样的信息。Page.User.Identity.Name只是返回用户登录时使用的名称,在本例中是工号。 我们的目标是,能不能实现Page.User.Identity.Name显示用户的真实名称,而不是工号,甚至还可以显示其他的一些信息。   要实现这样的功能,我的思路是自定义身份验证。下面就是我

陈希章@中国 1902

认识HttpContext.User

HttpContext.User,即IPrincipal .net源代码 namespace System.Security.Principal { /// <summary>Defines the basic functionality of a principal object.</summary> [__DynamicallyInvoka...

weixin_30466039的博客 849

关于jwt做登陆通过Response.HttpContext.User.Identity.Name获取jwt存的用户数据为null

jwt登录验证获取Response.HttpContext.User.Identity.Name为null的情况

si_yin的博客 2324

使用HttpContext中的User属性来实现用户身份验证之用户验证票篇[转载]

 在我的上一篇《使用HttpContext中的User属性来实现用户身份验证》中已经讲了怎样来使用HttpContext.User属性来实现用户身份验证,并且还写了一个示例程序。但是,在上一篇文章中,我们使用的是系统缓存来保存用户的登录信息,这无疑是占用系统资源的一种做法,那有没有更好的办法呢?我在上一章中说过大家可以尝试使用用户验证票的方式来保存用户登录信息的,这种方式是基于Cookie原理

农民田园 1267

asp.net Context.User.Identity.Name说明

今天做了一个身份验证页面,基本实现功能,却不能显示当前用户姓名,自己MSDN半天一无所获,问题就在Context.User.Identity.Name;Context是HttpContext类,User属性Gets or sets security information for

3363

ASIC--DFT可测性设计工程师

DFT是什么? DFT是design for test(可测性设计)的缩写,就是在芯片设计过程中,加入可测性逻辑。有的公司把该职位归到前端设计,有的归到中端实现。 DFT职位大多分布于规模较大的数字IC设计公司里,因为大公司对芯片品质要求高,而且规模越大,芯片越贵,DFT就越复杂越重要。DFT主要是通过在芯片中加入可测性逻辑,等芯片制造出来,在ATE(AutomaticTestEquipmen...

TroubleMaker 2万+

ASP.NET Web API身份验证和授权

英语原文地址:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api 本文是作者所理解和翻译的内容。 这篇文章包括两部分:身份验证和授权。 身份验证用来确定一个用户的身份。例如,Alice用她的用户名和密码登陆系统,服务器用她的用户名和密码来确定她的身份。 授...

u014712365的博客 92

代码实现 —— 基于 STM32 的可见光通信系统课程设计

基于STM32F103ZET6,源码如需移植,需要修改定时器捕获通道引脚,及定时器,如果你也有这个课设任务,希望对你有所帮助。

不善挽留 1万+

ASP.NET CORE中使用Cookie身份认证

大家在使用ASP.NET的时候一定都用过FormsAuthentication做登录用户的身份认证,FormsAuthentication的核心就是Cookie,ASP.NET会将用户名存储在Cookie中。 现在到了ASP.NET CORE的时代,但是ASP.NET CORE中没有FormsAuthentication这个东西,那么怎么做身份认证呢?答案是ASP.NET CORE已经为我们内置了Cookie身份认证的功能,而且使用起来非常方便,注意本文是基于ASP.NET CORE 2.0版本来阐述Coo

极客神殿 1742

从零构建:基于Docker与FRR的OSPF虚拟网络实验室

本文详细介绍了如何利用Docker与FRR构建OSPF虚拟网络实验室,从环境设计到高级网络拓扑配置,再到实验验证与排错。通过容器化技术实现高效资源利用和快速部署,特别适合网络协议教学、企业网络架构验证等场景。

plum99的博客 222

SOME/IP协议详解「总目录」

SOME/IP系列文章总目录

雪云飞星的博客 2万+

使用HttpContext的User属性来实现用户验证

HttpContext类包含了个别HTTP请求的所有特定HTTP信息。这个示例主要是讲如何使用HttpContext类中的User属性来实现用户验证!用户验证是大部分ASP.net Web应用程序都要用到的,它在整个应用程序中占有很重要的地位,在.NET中,包含了很多种用户验证方式,如众所周知的PassPort认证,Windows认证,Form认证等等,可是这些都很难满足我们在实际应用中的需求

Don't think about what u can do,but do what u wanna do 1332

innovus:sroute 双层follow pin的做法

根据std cellpower pin的层次可以分成两种情况。

m0_61544122的博客 2731

使用HttpContext类中的User属性来实现用户验证!

HttpContext类包含了个别HTTP请求的所有特定HTTP信息。这个示例主要是讲如何使用HttpContext类中的User属性来实现用户验证! 用户验证是大部分ASP.NET WEB应用程序都要用到的,它在整个应用程序中占有很重要的地位,在.NET中,包含了很多种用户验证方式,如众所周知的PassPort认证,Windows认证,Form认证等等,可是这些都很难满足我们在实际应用中的需...

weixin_34289454的博客 265

AI处理器组合

编号0-3的处理器处于同一个链路中,编号4-7的处理器处于另外一个链路中,不通链路中的处理器不能通信,如下图所示。- 如果申请处理器个数为1,则选择同一链路,剩余可用的处理器数量为1个的最佳,其次是剩余3个的为次佳,然后是剩余2个,最后是剩余4个。输出为组合列表,当array=[0, 1, 4, 5, 6, 7] ,num=1时,输出为[[0], [1]]- 如果申请处理器个数为2,则选择同一链路剩余可用的处理器数量2个的为最佳,其次是剩余4个,最后是剩余3个。任务申请1个处理器。

面试高手的博客 1万+

DSP2837X CLA开发实战教程

摘要: 本文详细解析TI C2000 DSP中CLA协处理器的开发流程,以TMS320F28377D的cla_divide案例为例,展示浮点除法验证的实现方法。从基础配置(消息RAM管理、任务触发)到高级调试(ePWM计时、断点设置),涵盖全流程开发要点。重点分析CLA编程约束(禁用标准库、数学优化)、多任务调度及常见问题解决方案(如死锁、数据同步)。提供FPGA协同加速、电机控制等扩展方向,并推荐官方例程与硬件平台(如创龙TL2837xF-EVM)。开发时需注意.cla文件语法支持及调试技巧,以充分发挥C

6760

Web开发问题:HttpContext.Current.User.Identity.Name为null

问题描述: 做web登陆界面,调试时需要获取本机登陆名 public static string GetCurrentNTID() { string identityName = HttpContext.Current.User.Identity.Name; int splitIndex = identityName.IndexOf('\\'); ret...

今年依旧12岁 2275

玩转Docker | 使用Docker部署MediaCMS内容管理系统

玩转Docker | 使用Docker部署MediaCMS内容管理系统

qq_59334230的博客 2918

关于 HttpContext.Current.User.Identity.Name="" 的问题

环境:Windows Server 2012,Visual Studio 2015,ASP.NET MVC 最近在做一个项目的时候,本来是项目已经完成了的,然后用户提出,他们在用的时候,每次有新用户要用到该系统的时候都要去用户管理里面添加一个用户,这样不方便,可不可以用已有的AD账号,根据登陆电脑的用户直接登陆系统,不用输密码,这样方便点。 然后。。。 就出现标题的这个问题了 HttpC...

落花流水 2944

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jwt怎么获取当前登录用户_jwt - 如何在.NET Core Web API中获取当前用户(来自JWT Token) - SO中文参考 - www.soinside.com...

似乎很多人都在关注这个问题,所以我想分享一些我学习的信息,因为我不久前问过这个问题。它使一些事情变得更加清晰(至少对我来说)并且不那么明显(对我来说就像.NET新手一样)。正如MarcusHöglund在评论中提到的那样:它应该与“web api”相同。在ASP.NET Core Mvc和Web Api中合并使用相同的控制器。这绝对是真的,绝对正确。因为它在.NET和.NET Core中都是一样的...

weixin_39860583的博客 1611

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

自定义HttpContext.Current.User.Identity

在Global.asax中添加方法  protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) {             HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

Allen_白的专栏 7641

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

上一篇: ASP.NET Forms验证(自定义、角色提供程序)2
下一篇: 文件读写——C++
yangfcf
博客等级 码龄19年 10粉丝 19原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值