日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > asp.net >内容正文

asp.net

asp.net Forums 之HttpHandler和HttpModule

發(fā)布時(shí)間:2025/3/13 asp.net 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 asp.net Forums 之HttpHandler和HttpModule 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

我們先說(shuō)說(shuō)IHttpHandler和IHttpModule這兩個(gè)接口。
微軟的解釋為:
IHttpHandler: 定義 ASP.NET 為使用自定義 HTTP 處理程序同步處理 HTTP Web 請(qǐng)求而實(shí)現(xiàn)的協(xié)定。?
IHttpModule: 向繼承類提供模塊初始化和處置事件。?
有點(diǎn)看不懂,微軟的解釋一向如此。

那我們來(lái)看看代碼:
public interface IHttpHandler
{
?bool IsReusable { get; }
?void ProcessRequest(HttpContext context);
}
IsReusable獲取一個(gè)值,該值指示其他請(qǐng)求是否可以使用 System.Web.IHttpHandler 實(shí)例。
ProcessRequest()方法是處理請(qǐng)求的,System.Web.HttpContext 對(duì)象,它提供對(duì)用于為 HTTP 請(qǐng)求提供服務(wù)的內(nèi)部服務(wù)器對(duì)象(如 Request、Response、Session 和 Server)的引用。

public interface IHttpModule
{
?void Dispose();
?void Init(HttpApplication context);
}

Dispose()方法用于釋放資源。
Init()方法初始化這個(gè)HttpApplication,你可以在這時(shí)注冊(cè)各類事件,如:Application_BeginRequest,Application_AuthenticateRequest,Application_OnError等。

那IHttpHandler與IHttpModule有什么區(qū)別呢:
1.先后次序.先IHttpModule,后IHttpHandler. 注:Module要看你響應(yīng)了哪個(gè)事件,一些事件是在Handler之前運(yùn)行的,一些是在Handler之后運(yùn)行的
2.對(duì)請(qǐng)求的處理上:
IHttpModule是屬于大小通吃類型,無(wú)論客戶端請(qǐng)求的是什么文件,都會(huì)調(diào)用到它;例如aspx,rar,html的請(qǐng)求.
IHttpHandler則屬于挑食類型,只有ASP.net注冊(cè)過(guò)的文件類型(例如aspx,asmx等等)才會(huì)輪到調(diào)用它.
3.IHttpHandler按照你的請(qǐng)求生成響應(yīng)的內(nèi)容,IHttpModule對(duì)請(qǐng)求進(jìn)行預(yù)處理,如驗(yàn)證、修改、過(guò)濾等等,同時(shí)也可以對(duì)響應(yīng)進(jìn)行處理??? HttpHandler是HTTP請(qǐng)求的處理中心,真正地對(duì)客戶端請(qǐng)求的服務(wù)器頁(yè)面做出編譯和執(zhí)行,并將處理過(guò)后的信息附加在HTTP請(qǐng)求信息流中再次返回到HttpModule中。
??? HttpHandler與HttpModule不同,一旦定義了自己的HttpHandler類,那么它對(duì)系統(tǒng)的HttpHandler的關(guān)系將是“覆蓋”關(guān)系。

接下來(lái),我們?cè)賮?lái)看看ANF中的IHttpModule和IHttpHandler。
ForumsHttpModule類是ANF中自定義的HttpModule,它位于AspNetForums命名空間下。
在這個(gè)HttpModule中,自定義了

?

代碼 /// <summary>
/// 應(yīng)用程序初始化
/// </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);
}
}
}

?

?


應(yīng)用程序錯(cuò)誤處理 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;
// 增加異常信息不同級(jí)別顯示--開(kāi)始
// 如果為管理員,顯示異常詳細(xì)信息 by venjiang 2004-11-3
// 發(fā)布時(shí)注釋此代碼
// if(Users.GetUser().IsAdministrator)
// {
// context.Response.Write(context.Server.GetLastError().Message);
// return;
// }

// 增加異常信息不同級(jí)別顯示--結(jié)束

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);
}
}

?

?

當(dāng)安全模塊已建立用戶標(biāo)識(shí)時(shí)發(fā)生 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();
}

?

?

驗(yàn)證用戶授權(quán) 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);
}


}

?

?

響應(yīng)應(yīng)用程序請(qǐng)求開(kāi)始事件 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訪問(wèn)

//

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文件中配置

?

<!-- 指定應(yīng)用程序HttpModule -->
<httpModules>
<add name="AspNetForums" type="AspNetForums.ForumsHttpModule, AspNetForums.Components" />
</httpModules>

?

?

AvatarHttpHandler類是ANF中的自定義HttpHandler,它位于AspNetForums.Components.HttpHandler命名空間下。
這個(gè)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文件中的配置。

代碼 <!-- 指定應(yīng)用程序HttpHandlers -->
<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" />

?

?注:?本文引用了網(wǎng)絡(luò)上的一些資料。

轉(zhuǎn)載于:https://www.cnblogs.com/Jesong/archive/2010/06/04/1751598.html

總結(jié)

以上是生活随笔為你收集整理的asp.net Forums 之HttpHandler和HttpModule的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。