Web开发之ASP.Net:(3)ASP.Net原理
1.ASP.Net请求处理原理
Web开发就是Http请求 服务端处理 Http响应。ASP.Net Web开发就是基于ASP.Net技术对客户端请求进行处理和响应的开发。
1.1 ASP.NET技术简介
ASP.NET是一种动态网页技术,在服务器端运行.Net代码,动态生成HTML,然后响应给浏览器。
ASP.NET应用程序有主要有WebService(asmx)、WebForm(ashx、aspx)、MVC(Model, View , Controler)这几类。
ASP.NET里的常用文件分类如下:
HttpApplication
.asax 继承了HttpApplication类,包含 ASP.NET 应用程序级事件,全局应用程序(Global.asax),对所有的请求生效。
HttpHandler和HttpModule能做的在HttpApplication中都能做,之所以做区分,是为了便于模块化管理,避免HttpApplication中太臃肿。
一个HttpHandler只处理对应自己的一个或一批请求,不像HttpApplication会接收所有的请求。一个web应用程序按功能不同提供一批HttpHandler,HttpApplication根据请求的url将不同请求转到具体的HttpHandler去处理和响应。这样便于开发团队的并行工作,也有利于功能模块的灵活扩展和工程的维护。
一个HttpModule只为满足特定条件的请求注册一个或几个管道事件处理程序,达到实现一个功能的目的。可以建多个HttpModule,不同的功能放到不同HttpModule中实现。这样就不用把所有注册管道事件的代码都放在HttpApplication一个文件(即Global.asax)中,造成臃肿。
HttpHandler
.ashx 一般处理程序,ASP.NET核心程序,实现了IHttpHandler接口。
.aspx.cs 常用程序,用于编写大量的c#业务代码,和.aspx配套使用,实现了IHttpHandler。
.aspx 常用程序WebForm,用于创建网页和对网页进行编程的核心文件类型(前台文件_html,就相当于是Html模板页面),和.aspx.cs文件配套使用
.asmx 服务文件 供宿主 WebService在本地或远程使用,实现了IHttpHandler接口。
.cs 实现IHttpHandler接口的自定义类型,全局处理程序类,统一接管符合条件的请求的处理和响应,请求到此终止,不再往下面走。
HttpModule
.cs 实现IHttpModule接口的自定义类型,统一为所有页面注册事件处理程序,请求会继续往下走,直到到达处理该请求的.ashx或.aspx页面。
UserControl
.ascx 指明一个 ASP.NET 用户定义控件
Config
.config 配置文件,用于设置网站应用程序的各种属性
1.2 ASP.NET请求处理者:HttpHandler
浏览器过来的一个请求,ASP.NET服务端需要有一个相应的类对其进行处理并将处理结果响应给浏览器。
而这个类就是一个实现了IHttpHandler接口的类,是作为一个外部请求的目标程序的前提。(凡是没有实现此接口的类,就不能被浏览器请求。)
一般由*.ashx、*.aspx、*.asmx页面类或自定义的实现了IHttpHandler的类对请求进行处理和响应。
由支持ASP.NET的服务器调用和启动运行。一个HttpHandler程序负责处理它所对应的一个或一组URL地址的访问请求,并接收客户端发出的访问请求信息(请求报文)和产生响应内容(响应报文)。
简单的说:可以通过创建一个自己的HttpHandler程序来生成浏览器代码发送回客户端浏览器。
HttpHandler程序可以完成普通类程序所能完成的大多数任务:
(A).获取客户端HTML中Form表单提交的数据和URL参数
(B).访问服务器端的文件系统进行文件流操作
(C).访问数据库并进行CRUD操作
(D).访问其他类的成员。
(E).创建对客户端的响应消息内容
(F).对客户端进行响应。
1.3 ASP.NET系统对象
在一般处理程序里,通过ProcessRequest方法的参数HttpContext context调用
系统对象:
Page 指向页面自身的方式。作用域为页面执行期。
Request 读取客户端在Web请求期间发送的值(http请求报文数据)
Response 封装了页面执行期返回到Http客户端的输出(http响应报文数据)
Application 作用于整个程序运行期的状态对象
Session 会话期状态保持对象,用于跟踪单一用户的会话。
Cookie 客户端保持会话信息的一种方式
Server 提供对服务器上的方法和属性的访问
1.4 ASP.Net的Request和Response对象
Request(HttpRequest类型)和Response(HttpResponse类型)
二者都是ProcessRequest方法的参数Httpcontext context(请求上下文)的属性。
1.4.1 浏览器提交数据方式
1.表单:(数据在请求报文体中,格式:txtname=james&txtpwd=123)
<form action=“login.ashx” method=“post”>
<input type=“text” name=“txtname” />
<input type=“password” name=“txtpwd”/>
</form>
2.地址栏的URL参数,超链接的url,js指定的url(和表单的Get方式一样):键值对
http://127.0.0.1/login.ashx?txtname1=jordan&txtpwd1=123
1.4.2 Request:获取浏览器提交的参数
Request对象:获取浏览器请求数据的对象
1)QueryString属性(获取GET请求参数):
获取通过GET方式传来的数据 浏览器:超链接,和表单Method=get
示例:context.Request.QueryString[“txtname1”]
2)Form 属性(获取POST请求参数):
获取通过POST方式传来的数据 表单method=post
示例:context.Request.Form[“txtname”]
Params 属性:客户端提交的数据集合
3)Params属性(获取所有请求类型的参数)
(A)获取QueryString Form ServerVariables Cookies项的信息
(B)能用Form的地方、能用QueryString的地方都能用Params
for (int i = 0; i < context.Request.Params.Keys.Count; i )
{
string key = context.Request.Params.Keys[i];
context.Response.Write(key "====" context.Request.Params[key] "<br />");
}
获取到的部分信息列表:
ALL_HTTP====HTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:/ HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:zh-cn HTTP_HOST:localhost:1700 HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; @A/h9/=9MV]kICVz]I=_PjxR|>awt&Kd9ICc,/; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
ALL_RAW====Connection: Keep-Alive Accept: / Accept-Encoding: gzip, deflate Accept-Language: zh-cn Host: localhost:1700 User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; @A/h9/=9MV]kICVz]I=_PjxR|>awt&Kd9ICc,/; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
APPL_PHYSICAL_PATH====E:\课件\sln0906\
AUTH_TYPE====NTLM
AUTH_USER====XP--20120913MDL\Administrator
AUTH_PASSWORD====
LOGON_USER====XP--20120913MDL\Administrator
REMOTE_USER====XP--20120913MDL\Administrator
CONTENT_LENGTH====0
LOCAL_ADDR====127.0.0.1
PATH_INFO====/sln0906/06-Params.ashx
PATH_TRANSLATED====E:\课件\sln0906\06-Params.ashx
QUERY_STRING====
REMOTE_ADDR====127.0.0.1
REMOTE_HOST====127.0.0.1
REMOTE_PORT====
REQUEST_METHOD====GET
SCRIPT_NAME====/sln0906/06-Params.ashx
SERVER_NAME====localhost
SERVER_PORT====1700
SERVER_PORT_SECURE====0
SERVER_PROTOCOL====HTTP/1.1
SERVER_SOFTWARE====
URL====/sln0906/06-Params.ashx
HTTP_CONNECTION====Keep-Alive
HTTP_ACCEPT====/
HTTP_ACCEPT_ENCODING====gzip, deflate
HTTP_ACCEPT_LANGUAGE====zh-cn
HTTP_HOST====localhost:1700
HTTP_USER_AGENT====Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; @A/h9/=9MV]kICVz]I=_PjxR|>awt&Kd9ICc,/; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
附:页面前端js版QueryString获取参数
function getQueryString(name) {
var reg = new RegExp("(^|&)" name "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null)
return unescape(r[2]);
return null;
}
1.4.3 Response:向浏览器输出数据
Response:允许开发人员对当前页面的输出流进行操作
Write方法----直接在页面上输出内容
Redirect方法----重定向到另外一个页面,服务器发送命令让浏览器跳转,前后的write()方法等将不再得到执行
End方法----结束输出
context.Response.Write(“我是从服务器输出到浏览器的数据!:)”);
Response.ContentType
ContentType 会影响客户端所看到的效果.默认的ContentType为 text/html 也就是网页格式.
代码如:
<% response.ContentType ="text/html" %>
<!--#i nclude virtual="/ContentType.html" --> 显示的为网页,
而
<% response.ContentType ="text/plain" %>
<!--#i nclude virtual="/sscript/ContentType.html" -->则会显示html原代码.
以下为一些常用的 ContentType
GIF images
<% response.ContentType ="image/gif" %>
<!--#i nclude virtual="/myimage.gif" -->
JPEG images
<% response.ContentType ="image/jpeg" %>
<!--#i nclude virtual="/myimage.jpeg" -->
TIFF images
<% response.ContentType ="image/tiff" %>
<!--#i nclude virtual="/myimage.tiff" -->
MICROSOFT WORD document
<% response.ContentType ="application/msword" %>
<!--#i nclude virtual="/myfile.doc" -->
RTF document
<% response.ContentType ="application/rtf" %>
<!--#i nclude virtual="/myfile.rtf" -->
MICROSOFT EXCEL document
<% response.ContentType ="application/x-excel" %>
<!--#i nclude virtual="/myfile.xls" -->
MICROSOFT POWERPOINT document
<% response.ContentType ="application/ms-powerpoint" %>
<!--#i nclude virtual="/myfile.pff" -->
PDF document
<% response.ContentType ="application/pdf" %>
<!--#i nclude virtual="/myfile.pdf" -->
ZIP document
<% response.ContentType ="application/zip" %>
<!--#i nclude virtual="/myfile.zip" -->
下面是更详细的ContentType
'ez' => 'application/andrew-inset',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'doc' => 'application/msword',
'bin' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'class' => 'application/octet-stream',
'so' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => 'application/pdf',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'bcpio' => 'application/x-bcpio',
'vcd' => 'application/x-cdlink',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'js' => 'application/x-javascript',
'skp' => 'application/x-koan',
'skd' => 'application/x-koan',
'skt' => 'application/x-koan',
'skm' => 'application/x-koan',
'latex' => 'application/x-latex',
'nc' => 'application/x-netcdf',
'cdf' => 'application/x-netcdf',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texinfo' => 'application/x-texinfo',
'texi' => 'application/x-texinfo',
't' => 'application/x-troff',
'tr' => 'application/x-troff',
'roff' => 'application/x-troff',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'ms' => 'application/x-troff-ms',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'xhtml' => 'application/xhtml xml',
'xht' => 'application/xhtml xml',
'zip' => 'application/zip',
'au' => 'audio/basic',
'snd' => 'audio/basic',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'kar' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'm3u' => 'audio/x-mpegurl',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'wav' => 'audio/x-wav',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'ief' => 'image/ief',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'png' => 'image/png',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'djvu' => 'image/vnd.djvu',
'djv' => 'image/vnd.djvu',
'wbmp' => 'image/vnd.wap.wbmp',
'ras' => 'image/x-cmu-raster',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'igs' => 'model/iges',
'iges' => 'model/iges',
'msh' => 'model/mesh',
'mesh' => 'model/mesh',
'silo' => 'model/mesh',
'wrl' => 'model/vrml',
'vrml' => 'model/vrml',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'asc' => 'text/plain',
'txt' => 'text/plain',
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'sgml' => 'text/sgml',
'sgm' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
'etx' => 'text/x-setext',
'xsl' => 'text/xml',
'xml' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'mxu' => 'video/vnd.mpegurl',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk'
1.5 ASP.Net请求处理原理
1.5.1静态和动态页面的请求处理
1.5.2 ASP.Net请求处理响应原理
(1)ASP.Net是通过aspnet_isapi.dll(IIS的可扩展程序,实现了IIS的接口)来与IIS交互的。而浏览器的请求则是交给IIS的。(像传输层的Socket的connect、accept、receive、send等方法不需要再出现在ASP.Net中了)
(2)ASP.Net从IIS接收到的请求,封装到HttpWorkerRequest类的对象中,交给HttpRuntime.ProcessRequest方法来处理。其工作是从HttpRuntime.ProcessRequest(HttpWorkerRequest wr)开始的,在HttpRuntime.ProcessRequest内部创建了高层的HttpApplication对象和Httpcontext(上下文),其工作任务就是用HttpApplication的ProcessRequest方法来处理包含在Httpcontext对象中的相关请求。
(3)ASP.Net为一般处理程序提供了IHttpHandler接口,ProcessRequest方法,Httpcontext对象(Httpcontext对象包含HttpRequest、HttpReponse属性)等,对Http协议中如拼接Http报文的繁琐工作做了封装。
HttpApplication的ProcessRequest方法根据请求地址调用相应的HttpHandler类来最终处理和响应请求。
下图是ASP.Net请求处理流程图:
1.5.3 ASP.Net请求处理流程(含页面生命周期)
HttpApplication的管道事件,针对整个应用程序的,不只是某个具体的页面类的ProcessRequest。
ASP.NET请求处理流程包含页面生命周期:
1.5.4 ASP.Net请求响应编译流程
2.HttpApplication:全局应用程序类(Global.asax)
注册HttpApplication的19个事件有三种方式:全局应用程序(Global.asax)中、HttpHandler中、HttpModel中
Application_BeginRequest事件 防盗链
<%@ Application Language="C#" %>
<script runat="server">
void Application_BeginRequest(object sender,EventArgs e)
{
string rawUrl = Request.RawUrl;
if (rawUrl.Contains("/images/"))
{
Response.ContentType = "image/jpeg";
Uri url = Request.Url;
Uri referrer = Request.UrlReferrer;
if (IsSameDomain(url, referrer))
{
}
else {
//盗链图片
string path = Request.MapPath("~/daolian.jpg");
Response.WriteFile(path);
//结束请求
Response.End();//终止请求,不再往下走
}
}
}
bool IsSameDomain(Uri url1,Uri url2)
{
return Uri.Compare(url1, url2, UriComponents.HostAndPort, UriFormat.SafeUnescaped, StringComparison.CurrentCultureIgnoreCase) == 0;
}
3.HttpHandler(自定义):全局处理程序类
拦截符合条件的请求,并进行统一的处理和响应,请求到这里终止。
3.1全局处理程序给图片加logo
(1)新建一个类 实现IHttphandler接口
(2)重写ProcessRequest方法,实现相应的功能(如加水印)
g.DrawImage(logo,x ,y ,logo.Width,logo.Height);
(3)配置web.config
<system.web>
<httpHandlers>
<add path="images//.jpeg" type="WaterMaker" verb="*"/>
<add path="images//.jpg" type="WaterMaker" verb="*" />
</httpHandlers>
</system.web>
带程序集名的配置
<httpHandlers>
<add path="Upload/Images////////.jpg" type="WaterMark,IProgram.CMS.UI.Portal" verb="*" />
</httpHandlers>
(4) 关于RawUrl //得到 /MyPhotos/images/07.jpg 本项目路径下的地址
Url.ToString(); //得到 http://localhost:1565/MyPhotos/images/07.jpg 带协议、网络地址、端口号的三级寻址
public class WaterMaker : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
//获取提交的图片路径
string path = context.Request.RawUrl;// 得到/MyPhotos/images/07.jpg
string path1 = context.Request.Url.ToString(); //得到http://localhost:1565/MyPhotos/images/07.jpg
path = context.Request.MapPath(path);
//相对于当前请求的文件的路径
string logoPath = context.Request.MapPath("../Logo/logo.png");
//绘制Logo
using (Image img = Image.FromFile(path))
{
using (Image logo = Image.FromFile(logoPath))
{
using (Graphics g = Graphics.FromImage(img))
{
int x =(img.Width-logo.Width)/3 ;
int y =(img.Height-logo.Height)/3;
g.DrawImage(logo,x ,y ,logo.Width,logo.Height);
//保存输出
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}
public bool IsReusable
{
get { throw new NotImplementedException(); }
}
}
3.2 全局处理程序和Request.UrlReferrer防盗链
// (1) 新建一个类
// (2) 实现IHttphandler 实现相应的功能(水印)
// (3) 配置web.config
// 在system.web节点下的httphandlers下添加
// 如果WaterMaker 类在当前网站
// <add verb="*" path="images//.jpg" type="WaterMaker"/>
// 如果WaterMaker类在另外一个程序集
// <add verb="*" path="images//.jpg" type="命名空间.WaterMaker,程序集"/>
public class Daolian : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
//获取提交的图片路径
string path = context.Request.RawUrl;
path = context.Request.MapPath(path);
Uri urlRef = context.Request.UrlReferrer;
Uri url = context.Request.Url;
//正常下载
if (IsSameDomain(urlRef, url))
{
context.Response.WriteFile(path);
}
//盗链下载
else
{
string daolianPath = context.Request.MapPath("../Dl/daolian.png");
context.Response.WriteFile(daolianPath);
}
}
//UriComponents.HostAndPort,比较两个路径的域名
//UriFormat.SafeUnescaped,具有保留意义的字符仍进行转义
//StringComparison.CurrentCultureIgnoreCase,使用区域敏感排序规则,当前区域比较,忽略大小写
bool IsSameDomain(Uri url1, Uri url2)
{
return Uri.Compare(url1, url2, UriComponents.HostAndPort, UriFormat.SafeUnescaped, StringComparison.CurrentCultureIgnoreCase)==0;
}
4.HttpModule:所有页面注册事件处理程序
如上所述,给图片加logo功能 使用全局处理程序(实现了IHttpHandler的自定义类)。
实现了IHttpModule的类,用来为所有页面统一添加管道事件处理程序,请求还是会继续往下走,直到到达处理该请求的.ashx或.aspx页面。
4.1 简单测试 控制所有页面事件
为所有页面注册BeginRequest事件
public class Test:IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest = new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;//该事件是HttpApplication类的context触发的
if (app != null)
{
app.Response.Write("hello world");
}
}
}
4.2 权限判断 要用到Session ,所以注册第9个事件AcquireRequestState
public class Test:IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
//获得状态 AcquireRequestState
context.AcquireRequestState = new EventHandler(context_AcquireRequestState);
}
void context_AcquireRequestState(object sender, EventArgs e)
{
//验证权限
HttpApplication app = sender as HttpApplication;
if (app != null)
{
if (!app.Request.RawUrl.ToLower().Contains("login.aspx"))
{
if (app.Session["user"] == null)
{
app.Response.Write("<script>alert('没有权限');window.location.href='Login.aspx?returnurl=" app.Request.RawUrl "'</script>");
app.Response.End(); //终止请求,不再往下走
}
}
}
}
}
完成后对在<system.web>下进行如下配置:
<httpModules>
<add name="ck" type="Test" />
</httpModules>
4.3 url重写原理 注册BeginRequest
//当用户输入路径是指定的格式时,用Context.RewritePath("新路径")方法重置到真实存在的页面去。
//1 新建一个类文件 实现IHttpModule接口
//2 重写IHttpModule的Init方法,注册请求开始时事件:context.BeginRequest
//3 在事件的方法中,对输入路径进行匹配,匹配成功则使用Context.RewritePath("新路径")方法重置
public class UrlReWrite:IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest = new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
//"http://localhost:1463/photos-12.htm"
if (app!=null)
{
string rawurl = app.Request.RawUrl;//
Regex regex = new Regex(@"/photos\-(\d{2})\.htm");
Match match = regex.Match(rawurl);
if (match.Success)
{
string s = match.Groups[1].Value;
app.Context.RewritePath("02Repeater-PhotoList01.aspx");
}
}
}
}
重写完成后对在<system.web>下进行如下配置:
<httpModules>
<add name="rewrite" type="DataBind.UrlReWrite" />
</httpModules>
4.4 url重写(配置方式) httpHandlers
1、引用微软提供的URLRewriter.dll组件
2、urlRewriter配置-实现对多个页面统一处理快捷方式:
(1)、<configuration>中增加
在<configSections>节点加入
<section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
(2)、<configuration>中增加自定义节点--在</configSections>之后
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/photos/(\d{2})\.html</LookFor>
<SendTo>~/03-PhotoDetails.aspx?pid=$1</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>
(3)system.web下增加
<httpHandlers>中加入
<add verb="*" path="*.html" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
5. Asp.Net开发中的路径处理
5.1 各种路径
绝对路径
c:\abc\123.jpg
相对路径
相对于被请求的文件,../返回上一级目录 和./ 相对于当前目录
根路径
相对于域名下的根路径 返回http://域名/路径 /85.gif
<img src="/85.gif" /> 相当于http://localhost:2972/85.gif
虚拟路径(asp.net中)
理解为相对于网站(站点)下的根路径 ~/85.gif
~/ 只有asp.net支持。
<asp:Image ID="Image1" runat="server" ImageUrl="~/85.gif" />
相当于http://localhost:2972/sln0917/85.gif
5.2 获取路径
5.2.1 取得控制台应用程序的根目录
Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径
AppDomain.CurrentDomain.BaseDirectory 获取基目录,用来探测程序集
5.2.2 取得Web应用程序的根目录
HttpRuntime.AppDomainAppPath.ToString();//获取承载在当前应用程序域中的应用程序的应用程序目录的物理驱动器路径。用于App_Data中获取
Server.MapPath("") 或者 Server.MapPath("~/");//返回与Web服务器上的指定的虚拟路径相对的物理文件路径
Request.ApplicationPath;//获取服务器上ASP.NET应用程序的虚拟应用程序根目录
如:string path = context.Request.ApplicationPath;
5.2.3 Aspnet中获取路径的方法
1.Request.ApplicationPath->当前应用的目录
ApplicationPath指的是当前的application(应用程序)的目录。
对应的--例如我的服务器上有两个web应用域名都是kl.com 一个映射到目录http://kl.com/1/ 另一个影射到 http://kl.com/2/,那么kl.com/1/就是第一个应用的ApplicationPath,kl.com/2/就是第二个应用的ApplicationPath。
2.Request.FilePath->对应于iis的虚拟目录的路径
如 URL http://kl.com/1/index.html/pathinfo
FilePath = /1/index.html
3.Request.Path->当前请求的虚拟路径
Path 是 FilePath 和 PathInfo 尾部的串联。例如 URL http://mockte.com/1/index.html/pathinfo
那么Path = /1/index.html/pathinfo
4.Request.MapPath(string url)->将url映射为iis上的虚拟目录
这个目录都是相对于application的根目录的
与Server.MapPath相比,不会包含类似c:/这样的路径
可以理解为是相对路径(对应的Server.MapPath就是绝对路径)
5.Server.MapPath(string url)->将url映射为服务器上的物理路径
例如 http://kl.com/1/index.html 假设你的应用程序在c:/iis/MySite中
那么就是 c:/iis/MySite/1/index.html
//本地路径转换成URL相对路径
private string urlconvertor(string imagesurl1)
{
string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
string imagesurl2 = imagesurl1.Replace(tmpRootDir, ""); //转换成相对路径
imagesurl2 = imagesurl2.Replace(@"\", @"/");
//imagesurl2 = imagesurl2.Replace(@"Aspx_Uc/", @"");
return imagesurl2;
}
//相对路径转换成服务器本地物理路径
private string urlconvertorlocal(string imagesurl1)
{
string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
string imagesurl2 = tmpRootDir imagesurl1.Replace(@"/", @"\"); //转换成绝对路径
return imagesurl2;
}
Server.MapPath获取该站点下某个虚拟路径的物理地址:
Server.MapPath的用法:
1.Server.MapPath("/") 应用程序根目录所在的位置 如 C:\Inetpub\wwwroot\
2.Server.MapPath("./") 表示所在页面的当前目录,等价于Server.MapPath("") 返回 Server.MapPath("")所在页面的物理文件路径
3.Server.MapPath("../")表示上一级目录的物理路径。
4.Server.MapPath("~/"),等效于Server.MapPath("~"),表示当前应用级程序的目录,如果是根目录,就是根目录,如果是虚拟目录,就是虚拟目录所在的位置 如:C:\Inetpub\wwwroot\Example\。
5.3 img标签src路径的赋值
var $divImg = $('<div class="img"><img width="30px"; height="38px" margin-top:10px; alt="无" src=' url '/></div>');//导致img标签的封闭字符被拼接到src中,致使路径以“/”结尾,而无法正确访问。
修改如下:
var $divImg = $('<div class="img"><img width="30px"; height="38px" margin-top:10px; alt="无" src=' url '></img></div>');