自定义一个叫 ReadOnlyXmlMembershipProvider 的 MembershipProvider,用 XML 作为用户储藏室
1. 配置 web.config
<membership defaultProvider="AspNetReadOnlyXmlMembershipProvider">
<providers>
<clear />
<add name="AspNetReadOnlyXmlMembershipProvider" type="OpenIdWebRingSsoProvider.Code.ReadOnlyXmlMembershipProvider" description="Read-only XML membership provider" xmlFileName="~/App_Data/Users.xml" />
</providers>
</membership>
2.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Security.Permissions;
using System.Web;
using System.Web.Hosting;
using System.Web.Security;
using System.Xml; public class ReadOnlyXmlMembershipProvider : MembershipProvider {
private Dictionary<string, MembershipUser> users;
private string xmlFileName; // MembershipProvider Properties
public override string ApplicationName {
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
} public override bool EnablePasswordRetrieval {
get { return false; }
} public override bool EnablePasswordReset {
get { return false; }
} public override int MaxInvalidPasswordAttempts {
get { throw new NotSupportedException(); }
} public override int MinRequiredNonAlphanumericCharacters {
get { throw new NotSupportedException(); }
} public override int MinRequiredPasswordLength {
get { throw new NotSupportedException(); }
} public override int PasswordAttemptWindow {
get { throw new NotSupportedException(); }
} public override MembershipPasswordFormat PasswordFormat {
get { throw new NotSupportedException(); }
} public override string PasswordStrengthRegularExpression {
get { throw new NotSupportedException(); }
} public override bool RequiresQuestionAndAnswer {
get { throw new NotSupportedException(); }
} public override bool RequiresUniqueEmail {
get { throw new NotSupportedException(); }
} // MembershipProvider Methods
public override void Initialize(string name, NameValueCollection config) {
// Verify that config isn't null
if (config == null) {
throw new ArgumentNullException("config");
} // Assign the provider a default name if it doesn't have one
if (string.IsNullOrEmpty(name)) {
name = "ReadOnlyXmlMembershipProvider";
} // Add a default "description" attribute to config if the
// attribute doesn't exist or is empty
if (string.IsNullOrEmpty(config["description"])) {
config.Remove("description");
config.Add("description", "Read-only XML membership provider");
} // Call the base class's Initialize method
base.Initialize(name, config); // Initialize _XmlFileName and make sure the path
// is app-relative
string path = config["xmlFileName"]; if (string.IsNullOrEmpty(path)) {
path = "~/App_Data/Users.xml";
} if (!VirtualPathUtility.IsAppRelative(path)) {
throw new ArgumentException("xmlFileName must be app-relative");
} string fullyQualifiedPath = VirtualPathUtility.Combine(
VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath),
path); this.xmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);
config.Remove("xmlFileName"); // Make sure we have permission to read the XML data source and
// throw an exception if we don't
FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, this.xmlFileName);
permission.Demand(); // Throw an exception if unrecognized attributes remain
if (config.Count > ) {
string attr = config.GetKey();
if (!string.IsNullOrEmpty(attr)) {
throw new ProviderException("Unrecognized attribute: " + attr);
}
}
} public override bool ValidateUser(string username, string password) {
// Validate input parameters
if (string.IsNullOrEmpty(username) ||
string.IsNullOrEmpty(password)) {
return false;
} try {
// Make sure the data source has been loaded
this.ReadMembershipDataStore(); // Validate the user name and password
MembershipUser user;
if (this.users.TryGetValue(username, out user)) {
if (user.Comment == password) { // Case-sensitive
// NOTE: A read/write membership provider
// would update the user's LastLoginDate here.
// A fully featured provider would also fire
// an AuditMembershipAuthenticationSuccess
// Web event
return true;
}
} // NOTE: A fully featured membership provider would
// fire an AuditMembershipAuthenticationFailure
// Web event here
return false;
} catch (Exception) {
return false;
}
} public override MembershipUser GetUser(string username, bool userIsOnline) {
// Note: This implementation ignores userIsOnline // Validate input parameters
if (string.IsNullOrEmpty(username)) {
return null;
} // Make sure the data source has been loaded
this.ReadMembershipDataStore(); // Retrieve the user from the data source
MembershipUser user;
if (this.users.TryGetValue(username, out user)) {
return user;
} return null;
} public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) {
// Note: This implementation ignores pageIndex and pageSize,
// and it doesn't sort the MembershipUser objects returned // Make sure the data source has been loaded
this.ReadMembershipDataStore(); MembershipUserCollection users = new MembershipUserCollection(); foreach (KeyValuePair<string, MembershipUser> pair in this.users) {
users.Add(pair.Value);
} totalRecords = users.Count;
return users;
} public override int GetNumberOfUsersOnline() {
throw new NotSupportedException();
} public override bool ChangePassword(string username, string oldPassword, string newPassword) {
throw new NotSupportedException();
} public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) {
throw new NotSupportedException();
} public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) {
throw new NotSupportedException();
} public override bool DeleteUser(string username, bool deleteAllRelatedData) {
throw new NotSupportedException();
} public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) {
throw new NotSupportedException();
} public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) {
throw new NotSupportedException();
} public override string GetPassword(string username, string answer) {
throw new NotSupportedException();
} public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) {
throw new NotSupportedException();
} public override string GetUserNameByEmail(string email) {
throw new NotSupportedException();
} public override string ResetPassword(string username, string answer) {
throw new NotSupportedException();
} public override bool UnlockUser(string userName) {
throw new NotSupportedException();
} public override void UpdateUser(MembershipUser user) {
throw new NotSupportedException();
} // Helper method
private void ReadMembershipDataStore() {
lock (this) {
if (this.users == null) {
this.users = new Dictionary<string, MembershipUser>(, StringComparer.InvariantCultureIgnoreCase);
XmlDocument doc = new XmlDocument();
doc.Load(this.xmlFileName);
XmlNodeList nodes = doc.GetElementsByTagName("User"); foreach (XmlNode node in nodes) {
MembershipUser user = new MembershipUser(
Name, // Provider name
node["UserName"].InnerText, // Username
null, // providerUserKey
null, // Email
string.Empty, // passwordQuestion
node["Password"].InnerText, // Comment
true, // isApproved
false, // isLockedOut
DateTime.Now, // creationDate
DateTime.Now, // lastLoginDate
DateTime.Now, // lastActivityDate
DateTime.Now, // lastPasswordChangedDate
new DateTime(, , )); // lastLockoutDate this.users.Add(user.UserName, user);
}
}
}
}
}
3.
谢谢浏览!
自定义一个叫 ReadOnlyXmlMembershipProvider 的 MembershipProvider,用 XML 作为用户储藏室的更多相关文章
- Spring自定义一个拦截器类SomeInterceptor,实现HandlerInterceptor接口及其方法的实例
利用Spring的拦截器可以在处理器Controller方法执行前和后增加逻辑代码,了解拦截器中preHandle.postHandle和afterCompletion方法执行时机. 自定义一个拦截器 ...
- JSTL,自定义一个标签的功能案例
1.自定义一个带有两个属性的标签<max>,用于计算并输出两个数的最大值: 2.自定义一个带有一个属性的标签<lxn:readFile src=“”>,用于输出指定文件的内容 ...
- 自定义View(7)官方教程:自定义View(含onMeasure),自定义一个Layout(混合组件),重写一个现有组件
Custom Components In this document The Basic Approach Fully Customized Components Compound Controls ...
- 自定义一个EL函数
自定义一个EL函数 一般就是一下几个步骤,顺便提供一个工作常用的 案例: 1.编写一个java类,并编写一个静态方法(必需是静态方法),如下所示: public class DateTag { pri ...
- 自定义一个可以被序列化的泛型Dictionary<TKey,TValue>集合
Dictionary是一个键值类型的集合.它有点像数组,但Dictionary的键可以是任何类型,内部使用Hash Table存储键和值.本篇自定义一个类型安全的泛型Dictionary<TKe ...
- SpringMVC 自定义一个拦截器
自定义一个拦截器方法,实现HandlerInterceptor方法 public class FirstInterceptor implements HandlerInterceptor{ /** * ...
- jQuery Validate 表单验证插件----自定义一个验证方法
一.下载依赖包 网盘下载:https://yunpan.cn/cryvgGGAQ3DSW 访问密码 f224 二.引入依赖包 <script src="../../scripts/j ...
- Volley HTTP库系列教程(5)自定义一个Volley请求
Implementing a Custom Request Previous Next This lesson teaches you to Write a Custom Request parse ...
- 在String()构造器不存在的情况下自定义一个MyString()函数,实现如下内建String()方法和属性:
在String()构造器不存在的情况下自定义一个MyString()函数,实现如下内建String()方法和属性: var s = new MyString("hello"); s ...
随机推荐
- Windows Error Code(windows错误代码详解)
0 操作成功完成. 1 功能错误. 2 系统找不到指定的文件. 3 系统找不到指定的路径. 4 系统无法打开文件. 5 拒绝访问. 6 句柄无效. 7 存储控制块被损坏. 8 存储空间不足,无法处理此 ...
- 连接SQL SERVER 2008需要加端口号
VC2010 ADO 连接SQL SERVER 2008,127.0.0.1,1433,要加上端口,否则连不上.注意:地址和端口之间使用逗号隔开. 连接SQL SERVER 2000可以不加端口号,使 ...
- Android JNI HelloWorld实现
创建一个JNIDemo的Android工程 在项目下创建一个文件夹jni.(注意必须是jni目录) 在jni目录下创建两个文件:Android.mk 和 first_jni.c(.c文件的名字可以任意 ...
- 使用6to5,让今天就来写ES6的模块化开发!
http://es6rocks.com/2014/10/es6-modules-today-with-6to5/?utm_source=javascriptweekly&utm_medium= ...
- [ay原创作品]用wpf写了个模仿36Kr网站登录背景的效果
这里我借鉴了,上周比较火的一个前端文章,人家用js去写的,地址 自己用wpf也写了一个,但是它的 粒子比较,然后连线算法真的很差,他创建了一个加入鼠标点的集合,2个集合进行比较,并且粒子会向鼠标靠近 ...
- 【最新图文教程】WinCE5.0中文模拟器SDK(VS2008)的配置
http://www.blogbus.com/antiblood-logs/204402631.html 经过几天的查找,终于找到了一篇文章是讲VS2008 怎么集成wince5.0 的模拟器的,这里 ...
- clearfix清除浮动进化史
我想大家在写CSS的时候应该都对清除浮动的用法深有体会,今天我们就还讨论下clearfix的进化史吧. clearfix清除浮动 首先在很多很多年以前我们常用的清除浮动是这样的. .clear{cle ...
- Codeforces Round #292 (Div. 1) C. Drazil and Park 线段树
C. Drazil and Park 题目连接: http://codeforces.com/contest/516/problem/C Description Drazil is a monkey. ...
- 将ASP.NET Core应用程序部署至生产环境中(CentOS7)(转)
阅读目录 环境说明 准备你的ASP.NET Core应用程序 安装CentOS7 安装.NET Core SDK for CentOS7. 部署ASP.NET Core应用程序 配置Nginx 配置守 ...
- 前沿技术解密——VirtualDOM
作为React的核心技术之一Virtual DOM,一直披着神秘的面纱. 实际上,Virtual DOM包含: Javascript DOM模型树(VTree),类似文档节点树(DOM) DOM模型树 ...