asp.net Forums 之HttpHandler和HttpModule
我們先說說IHttpHandler和IHttpModule這兩個接口。
微軟的解釋為:
IHttpHandler: 定義 ASP.NET 為使用自定義 HTTP 處理程序同步處理 HTTP Web 請求而實現的協定。?
IHttpModule: 向繼承類提供模塊初始化和處置事件。?
有點看不懂,微軟的解釋一向如此。
那我們來看看代碼:
public interface IHttpHandler
{
?bool IsReusable { get; }
?void ProcessRequest(HttpContext context);
}
IsReusable獲取一個值,該值指示其他請求是否可以使用 System.Web.IHttpHandler 實例。
ProcessRequest()方法是處理請求的,System.Web.HttpContext 對象,它提供對用于為 HTTP 請求提供服務的內部服務器對象(如 Request、Response、Session 和 Server)的引用。
public interface IHttpModule
{
?void Dispose();
?void Init(HttpApplication context);
}
Dispose()方法用于釋放資源。
Init()方法初始化這個HttpApplication,你可以在這時注冊各類事件,如:Application_BeginRequest,Application_AuthenticateRequest,Application_OnError等。
那IHttpHandler與IHttpModule有什么區別呢:
1.先后次序.先IHttpModule,后IHttpHandler. 注:Module要看你響應了哪個事件,一些事件是在Handler之前運行的,一些是在Handler之后運行的
2.對請求的處理上:
IHttpModule是屬于大小通吃類型,無論客戶端請求的是什么文件,都會調用到它;例如aspx,rar,html的請求.
IHttpHandler則屬于挑食類型,只有ASP.net注冊過的文件類型(例如aspx,asmx等等)才會輪到調用它.
3.IHttpHandler按照你的請求生成響應的內容,IHttpModule對請求進行預處理,如驗證、修改、過濾等等,同時也可以對響應進行處理??? HttpHandler是HTTP請求的處理中心,真正地對客戶端請求的服務器頁面做出編譯和執行,并將處理過后的信息附加在HTTP請求信息流中再次返回到HttpModule中。
??? HttpHandler與HttpModule不同,一旦定義了自己的HttpHandler類,那么它對系統的HttpHandler的關系將是“覆蓋”關系。
接下來,我們再來看看ANF中的IHttpModule和IHttpHandler。
ForumsHttpModule類是ANF中自定義的HttpModule,它位于AspNetForums命名空間下。
在這個HttpModule中,自定義了
?
代碼 /// <summary>/// 應用程序初始化
/// </summary>
/// <param name="application"></param>
public void Init(HttpApplication application)
{
// Wire-up application events
//
application.BeginRequest += new EventHandler(this.Application_BeginRequest);
application.AuthenticateRequest += new EventHandler(Application_AuthenticateRequest);
application.Error += new EventHandler(this.Application_OnError);
application.AuthorizeRequest += new EventHandler(this.Application_AuthorizeRequest);
#if DEBUG
application.ReleaseRequestState += new EventHandler(this.Application_ReleaseRequestState);
#endif
ForumConfiguration forumConfig = ForumConfiguration.GetConfig();
if (forumConfig != null
&& forumConfig.IsBackgroundThreadingDisabled == false)
{
if (emailTimer == null)
emailTimer = new Timer(new TimerCallback(ScheduledWorkCallbackEmailInterval), application.Context, EmailInterval, EmailInterval);
if (forumConfig.IsIndexingDisabled == false
&& statsTimer == null)
{
statsTimer = new Timer(new TimerCallback(ScheduledWorkCallbackStatsInterval), application.Context, StatsInterval, StatsInterval);
}
}
}
?
?
應用程序錯誤處理 Application_OnError
?
代碼 private void Application_OnError(Object source, EventArgs e){
ForumConfiguration forumConfig = ForumConfiguration.GetConfig();
string defaultLanguage = forumConfig.DefaultLanguage;
HttpApplication application = (HttpApplication) source;
HttpContext context = application.Context;
ForumException forumException;
string html;
StreamReader reader;
// 增加異常信息不同級別顯示--開始
// 如果為管理員,顯示異常詳細信息 by venjiang 2004-11-3
// 發布時注釋此代碼
// if(Users.GetUser().IsAdministrator)
// {
// context.Response.Write(context.Server.GetLastError().Message);
// return;
// }
// 增加異常信息不同級別顯示--結束
if (context.Server.GetLastError().GetBaseException() is ForumException)
{
forumException = (ForumException) context.Server.GetLastError().GetBaseException();
switch (forumException.ExceptionType)
{
case ForumExceptionType.DataProvider:
// We can't connect to the data store
//
reader = new StreamReader(context.Server.MapPath("~/Languages/" + defaultLanguage + "/errors/DataStoreUnavailable.htm"));
html = reader.ReadToEnd();
reader.Close();
html = html.Replace("[DATASTOREEXCEPTION]", forumException.Message);
context.Response.Write(html);
context.Response.End();
break;
case ForumExceptionType.UserInvalidCredentials:
forumException.Log();
break;
case ForumExceptionType.AccessDenied:
forumException.Log();
break;
case ForumExceptionType.AdministrationAccessDenied:
forumException.Log();
break;
case ForumExceptionType.ModerateAccessDenied:
forumException.Log();
break;
case ForumExceptionType.PostDeleteAccessDenied:
forumException.Log();
break;
case ForumExceptionType.PostProblem:
forumException.Log();
break;
case ForumExceptionType.UserAccountBanned:
forumException.Log();
break;
// LN 6/9/04: New exception added
case ForumExceptionType.ResourceNotFound:
//context.Response.Write(context.Server.GetLastError().Message);
forumException.Log();
break;
case ForumExceptionType.UserUnknownLoginError:
forumException.Log();
break;
}
}
else
{
forumException = new ForumException(ForumExceptionType.UnknownError, context.Server.GetLastError().Message, context.Server.GetLastError());
forumException.Log();
}
if (forumException.ExceptionType == ForumExceptionType.UnknownError)
{
if ((context.IsCustomErrorEnabled) && (!context.Request.Url.IsLoopback))
ForumContext.RedirectToMessage(context, forumException);
}
else
{
//context.Response.Write(context.Server.GetLastError().Message);
ForumContext.RedirectToMessage(context, forumException);
}
}
?
?
當安全模塊已建立用戶標識時發生 Application_AuthenticateRequest
?
代碼 private void Application_AuthenticateRequest(Object source, EventArgs e){
HttpContext context = HttpContext.Current;
Provider p = null;
ExtensionModule module = null;
// Only continue if we have a valid context
//
if ((context == null) || (context.User == null))
return;
try
{
// Logic to handle various authentication types
//
switch (context.User.Identity.AuthenticationType.ToLower())
{
// Microsoft passport
case "passport":
p = (Provider) ForumConfiguration.GetConfig().Extensions["PassportAuthentication"];
module = ExtensionModule.Instance(p);
module.ProcessRequest();
break;
// Windows
case "negotiate":
p = (Provider) ForumConfiguration.GetConfig().Extensions["WindowsAuthentication"];
module = ExtensionModule.Instance(p);
module.ProcessRequest();
break;
default:
ForumContext.Current.UserName = context.User.Identity.Name;
break;
}
}
catch (Exception ex)
{
ForumException forumEx = new ForumException(ForumExceptionType.UnknownError, "Error in AuthenticateRequest", ex);
forumEx.Log();
throw forumEx;
}
// 獲取用戶角色
Roles roles = new Roles();
roles.GetUserRoles();
}
?
?
驗證用戶授權 Application_AuthorizeRequest
?
代碼 private void Application_AuthorizeRequest(Object source, EventArgs e){
HttpApplication application = (HttpApplication) source;
HttpContext context = application.Context;
// Track anonymous users
//
Users.TrackAnonymousUsers();
// Do we need to force the user to login?
//
if (Users.GetUser().ForceLogin)
{
Moderate.ToggleUserSettings(ModerateUserSetting.ToggleForceLogin, Users.GetUser(), 0);
context.Response.Redirect(Globals.GetSiteUrls().Logout, true);
}
}
?
?
響應應用程序請求開始事件 Application_BeginRequest
?
代碼 private void Application_BeginRequest(Object source, EventArgs e){
if (HttpContext.Current.Request.Path.IndexOf('\\') >= 0 ||
Path.GetFullPath(HttpContext.Current.Request.PhysicalPath) != HttpContext.Current.Request.PhysicalPath)
{
throw new HttpException(404, "not found");
}
//2005-6-25
//阻止IP訪問
//
try
{
HttpApplication application = (HttpApplication) source;
HttpContext context = application.Context;
if (application == null
|| context == null)
return;
// Url Rewriting
string newPath = null;
string path = context.Request.Path;
string query = context.Request.Url.Query;
bool isReWritten = RewriteUrl(path, query, out newPath);
if (isReWritten && newPath != null)
context.RewritePath(newPath);
ForumContext frmContext = CreateForumContext(context);
frmContext.CurrentUrl = context.Request.RawUrl.ToString();
// 2005/04/07
//safe to set url rewrite data;
if (isReWritten && newPath != null)
{
frmContext.IsUrlReWritten = true;
}
// Capture any pingback information
//
CaptureForumPingback();
// Are the forums disabled?
//
if ((Globals.GetSiteSettings().ForumsDisabled) && (HttpContext.Current.Request.Url.Host != "localhost"))
{
ForumConfiguration forumConfig = ForumConfiguration.GetConfig();
string defaultLanguage = forumConfig.DefaultLanguage;
// Forums is disabled
//
StreamReader reader = new StreamReader(context.Server.MapPath("~/Languages/" + defaultLanguage + "/errors/ForumsDisabled.htm"));
string html = reader.ReadToEnd();
reader.Close();
context.Response.Write(html);
context.Response.End();
}
}
catch (Exception ex)
{
ForumException forumEx = new ForumException(ForumExceptionType.UnknownError, "Unknown error in BeginRequest", ex);
forumEx.Log();
}
if (HttpContext.Current.Request.Path.ToLower().IndexOf("msgs/default") < 0)
{
if (BlockedIpAddresses.AddressIsBlocked(Globals.IPAddress))
throw new ForumException(ForumExceptionType.BlockedIpAddress);
}
}
?
?
等事件。
在Web.Config文件中配置
?
<!-- 指定應用程序HttpModule --><httpModules>
<add name="AspNetForums" type="AspNetForums.ForumsHttpModule, AspNetForums.Components" />
</httpModules>
?
?
AvatarHttpHandler類是ANF中的自定義HttpHandler,它位于AspNetForums.Components.HttpHandler命名空間下。
這個HttpHandler主要用于處理用戶頭像的處理。
?
代碼 public void ProcessRequest(HttpContext context){
try
{
Avatar userAvatar = Resources.GetAvatar(int.Parse(context.Request.QueryString["UserID"]));
context.Response.ContentType = userAvatar.ContentType;
context.Response.OutputStream.Write(userAvatar.Content, 0, userAvatar.Length);
context.Response.Cache.SetCacheability(HttpCacheability.Public);
// Terry Denham 7/16/2004
// changing default cache for avatars from 1 day to 30 minutes
context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
context.Response.Cache.SetAllowResponseInBrowserHistory(true);
context.Response.Cache.SetValidUntilExpires(true);
context.Response.Cache.VaryByParams["UserID"] = true;
}
catch
{
}
}
?
?
在Web.Config文件中的配置。
<httpHandlers>
<add verb="GET" path="avatar.aspx" type="AspNetForums.Components.HttpHandler.AvatarHttpHandler, AspNetForums.Components" />
<add verb="GET" path="vcard.aspx" type="AspNetForums.Components.HttpHandler.VCardHttpHandler, AspNetForums.Components" />
?
?注:?本文引用了網絡上的一些資料。
轉載于:https://www.cnblogs.com/Jesong/archive/2010/06/04/1751598.html
總結
以上是生活随笔為你收集整理的asp.net Forums 之HttpHandler和HttpModule的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何向mysql导入数据库(。sql文件
- 下一篇: C++ primer 1.2 初窥输入输