您的位置:首页 > 移动开发

aspnetcdn 例子, 中文注释之 MyGlobalApplication.cs

2014-11-16 21:48 337 查看
aspnetcdn 一共分为两个工程. 一个为aspnetcdn.dll 工程, 一个是事例网站.

事例网站主要的文件便是 App_Code/MyGlobalApplication.cs

以下是 v0.1的代码的中文注释

using System;
using System.Collections.Generic;
using System.Web;

//使用aspnetcdn的网站必须继承aspnetcdn.AspNetApplication并且override CreateWebsiteRequest方法
//然后在Global.asax中引用:<%@ Application Language="C#" Inherits="MyGlobalApplication" %>
public class MyGlobalApplication : aspnetcdn.AspNetApplication
{
///override这个方法后, 这个方法就会被BeginRequest的时候被调用
protected override aspnetcdn.WebsiteRequest CreateWebsiteRequest()
{
//在这个例子中, 使用cookie来记住该重定向去example1还是example2指向的网站.
HttpCookie cookie;

string cdnr=Request.QueryString["cdnredirect"];
if (!string.IsNullOrEmpty(cdnr))
{
cookie = new HttpCookie("cdnredirect", cdnr);
cookie.Path = "/";
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
else
{
//为了让例子的首页总是能运行, 所以判断如果为首页, 则返回null, 即是不做重定向, 使用本站的aspx和资源
if (Request.Path == "/" || Request.Path.Equals("/default.aspx", StringComparison.OrdinalIgnoreCase))
return null;
//尝试寻找cookie
cookie = Request.Cookies["cdnredirect"];
if (cookie != null)
cdnr = cookie.Value;
}

//如果识别出要重定向example1的话
if (cdnr == "example1")
{
//websiteid主要是用来区分缓存和其它类型的共享资源
long websiteid = 1;

//设定要重定向的网址. 这里使用原网址. 开发者是可以自行对网址进行修改的.
string newpathquery = this.Request.Url.PathAndQuery;

//HOST头是指要向目标服务器获取哪个网站的内容. 这和服务器本身的域名并不需要对应.
string newhostheader = "homehttp.com";

//这里指定的是服务器的名字或IP. 如果域名本身没有指向到服务器, 那么就需要指定为ip
//注意, 这里一直都是处于可编程的状态, 开发者可以根据当前请求的COOKIES之类的信息, 去指派不同的服务器来达到分流的目的.
string servername = "homehttp.com";
int serverport = 80;

Uri uri = new Uri("http://" + newhostheader + newpathquery);

return new aspnetcdn.WebsiteRequest(websiteid, uri, servername, serverport);
}

//example2同理, 就不做解释.
if (cdnr == "example2")
{
long websiteid = 2;
string newpathquery = this.Request.Url.PathAndQuery;
string newhostheader = "forums.asp.net";
string servername = "forums.asp.net";
int serverport = 80;
Uri uri = new Uri("http://" + newhostheader + newpathquery);
return new aspnetcdn.WebsiteRequest(websiteid, uri, servername, serverport);
}

//当这个函数返回null的时候, 就表示希望当前网站的内容被执行了.
//也就是说, 如果上面从来不返回任何WebsiteRequest实例, 那么aspnetcdn就不起效果, 网站就和普通的ASP.NET一样运行.
return null;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: