Location access in ASP.NET
I have admin area of my site: http://www.mysite.com/webadmin and I want to protect it by role (I'm using ASP.NET forms auth), so that only a user with the role "admin" could access it. In web.config I added this entry:
&开发者_StackOverflowlt;location path="WebAdmin">
<system.web>
<authorization>
<deny users="*"/>
<allow roles="admin"/>
</authorization>
</system.web>
</location>
and it "sort of" works - it redirects you to the login page if you are not in role "admin". But I don't want that, I want to show an error page instead. Any way I could control that behavior?
Thank you, Andrey
You can change the URL your file thinks is the login page via web.config. (See http://www.15seconds.com/issue/020220.htm.)
Consider substituting your custom error page url for the real login URL in configuration.
Edit:
The web.config approach is viable if implementing this as a general solution throughout an entire virtual directory. (Attempting to configure custom loginUrl's under a <location>
element in web.config will result in a configuration error.)
You can have finer-grained control of this behavior imperatively by injecting code such as this in your admin page (or a base class for your admin pages):
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (!User.IsInRole("admin"))
{
Response.Redirect("~/ErrorPage.aspx?reason=denied");
}
}
You may also look into creating an HttpModule
, or tapping into your Global.asax, to handle authorization in a more general way without relying on page inheritance. See http://msdn.microsoft.com/en-us/library/ms227673.aspx. Use the BeginRequest
event to inspect the URL path, and if it matches your pattern, deliver the error or redirect you want to deliver.
精彩评论