自定义一个叫 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 ...
随机推荐
- EntityFramework IEnumerable,IQueryable ,Include
使用IQueryable using (var db = new CentaStaffEntities()) { IQueryable<Staff> queryablestaffs = d ...
- loghelper.cs 代码
唉,网上到处找一圈,真是麻烦,自己结合别人写的,重新整理一个. 这个破玩意最大的作用就是写微信那种没法顺利断点调试的程序的时候,在需要的地方写日志,然后去查看.真是回到当年用DW4写php的年代了,可 ...
- cmd for 循环拷贝文件
这几天忙活部署测试环境, 中途需要拷贝 文件, 直接贴code吧: ::/定义原路径 set source=seventrat_test_backend,seventrat_test_frontend ...
- android 页面跳转,数据回传
package com.example.firstpg.firstpg; import android.support.v7.app.ActionBarActivity; import android ...
- GTD时间管理(3)---项目
一:什么是项目? 一个项目是由多步骤,多阶段组成的,不可能一步到位的. 项目分为可大可小. 魔兽世界这个程序是一个项目,是一个用10年开发的大型项目 搭建一个博客也可以成为一个项目,可以用一天时间去搭 ...
- 八卦一下黄晓明和Angelababy的电话号码
最新一期20150605的<奔跑吧兄弟>真是太搞笑了,邓超被大家整的... 但这一期有个细节引起了我的注意,就是Angelababy在现场打电话给黄晓明,而拨键声音十分清晰.一些拥有“绝对 ...
- mac os 中安装memcahed
1.先安装macport sudo port selfupdate #更新当前Marport (如果port 不可以时可以考虑此操作) sudo prot -d selfupdate #替换更 ...
- 【BootStrap】初步教程
<span style="font-family: Arial, Helvetica, sans-serif;">最近刚刚接触到BootStrap,在这里总结一下Boo ...
- Activemq消息类型
Activemq消息类型JMS规范中的消息类型包括TextMessage.MapMessage.ObjectMessage.BytesMessage.和StreamMessage等五种.ActiveM ...
- 2.C#中泛型在方法Method上的实现
阅读目录 一:C#中泛型在方法Method上的实现 把Persion类型序列化为XML格式的字符串,把Book类型序列化为XML格式的字符串,但是只写一份代码,而不是public static s ...