Web.config中的location設定
前言
一般我們使用Asp.NET時,如果使用Form驗証方式的話,會設定Default的Page,當驗証失效時,要登出系統的話,該如何設定呢?
實作
在Web.config中有個location的Tag,是來指定特定資源做其他的設定,如登出會有一支程式叫logout.ashx,它就不需要一定要登入後才能執行到。或是有些程式,如公告的程式,就不需要在Form驗証之內。
- 設定Form的驗証
<authorization>
<allow users="*"/>
</authorization>
<authentication mode="Forms">
<forms name=".RAuth" loginUrl="Login.aspx" protection="All" timeout="20" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="Login.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false"/>
</authentication>
- 設定排除在Form的驗証之外
<location path="Logout.ashx">
<system.web>
<authorization>
<allow users="*"/>
<allow users="?"/>
</authorization>
</system.web>
</location>
在設定location的Path時,它好像不認得~/這個,因為有次我設成~/Logout.ashx時,它就會一直跑去Login.aspx。不過,設排除是特別的需求啦,除非您像我一樣,User輸入帳號的Page跟我設定的Default 登入Page不同。
- Logout.ashx做的事(主要是把Cookie給清掉)
<%@ WebHandler Language="VB" Class="Logout" %> Imports System Imports System.Web Imports System.Web.Security Imports System.Collections.Generic Public Class Logout : Implements IHttpHandler Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest Dim cookiesToClear As New List(Of String) For Each cookieName As String In context.Request.Cookies Dim cookie As HttpCookie = context.Request.Cookies(cookieName) cookiesToClear.Add(cookie.Name) Next For Each name As String In cookiesToClear Dim cookie As HttpCookie = New HttpCookie(name, String.Empty) cookie.Expires = DateTime.Today.AddYears(-1) context.Response.Cookies.Set(cookie) Next '到其他首頁 Dim strTop As String = GetOtherURL(); context.Response.Write("<script language='javascript'>top.window.location.href='" & strTop & "'</script>") End Sub Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return True End Get End Property End Class
http://msdn.microsoft.com/zh-tw/library/b6x6shw7(VS.80).aspx
http://msdn.microsoft.com/zh-tw/library/6hbkh9s7(VS.80).aspx
http://msdn.microsoft.com/zh-tw/library/55th21y4(VS.80).aspx
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^