I am using ASP.NET and I want to be able to redirect user to another page from web config.
I have number of restrictions like:
<location path="Structures.aspx">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="*" />
</authorization>
</system.web>
</location>
And it will be great if I redirect user to some page. I saw this post but it's not what I was looking for.
I need to do it in web.config and not in code behind. Thanks!
Assuming you want to handle all "Unauthorized" errors:
<customErrors defaultRedirect="Error.aspx" mode="On">
<error statusCode="401" redirect="Unauthorized.aspx" />
<error statusCode="403" redirect="Forbidden.aspx" />
</customErrors>
Any 401 (unauthorized) requests will be forwarded to Unauthorized.aspx
.
alternatively, you'll need to perform the check in your Page_Load
event. If this seems tedious you can always create a base page class for all pages that are supposed to be admin-only and perform the check there. e.g.
// base class
public class AdminOnlyPage : Page
{
/*...*/ Page_Load(Object sender, EventArgs e)
{
/* check if the user is admin otherwise reject and redirect */
}
}
// Your "Structures.aspx" page
public class Structures : AdminOnlyPage
{
}
I noticed my app is redirecting back to login page using "302 Found" code with "Location" header set. Since my login page happens to be in external application that just shares the same server, I couldn't modify it.
Instead, I added this to my global.asax:
protected void Application_EndRequest(Object sender, EventArgs e)
{
if (Response.Status.StartsWith("302")
&&
Request.IsAuthenticated
&&
Response.RedirectLocation.StartsWith(System.Web.Security.FormsAuthentication.LoginUrl))
{
//log.Trace("Preventing redirection from app to login form since user is already logged in. It's authorization issue, not authentication.");
Response.Clear();
Response.Redirect("~/AccessDenied.aspx");
}
}
来源:https://stackoverflow.com/questions/14731707/redirect-user-to-another-page-from-web-config-when-his-role-has-not-enough-permi