Reputation: 2348
Within my ASP.NET App I am using a Method to check user permissions to decide whether the user can view the page, or get redirected to the "Invalid Permissions" page.
Since adding this Permission Redirect on the Master Page would cause an infinite loop, I am forced to apply it to all pages. I do not want to have to copy this Method onto every page, so I would like to create a class within my Web App which holds this Method so I can use it globally across my app.
I have had no formal training, but my gut is telling me that it's bad practice to place a Response.Redirect or any "Web" functions in a class? Am I correct? And if so, is there a better way to go about this?
Upvotes: 1
Views: 3219
Reputation: 64218
First things first, your original question:
Bad practice to have a Response.Redirect within a class in ASP.NET?
Yes I believe this is a bad practice. It's safer to pass a delegate, then your 'AuthorizeRequest' method can call the delegate. Here is an example:
public static void AuthorizeRequest(Action<string> redirect)
{
if( /*whatever*/ )
redirect("/InvalidPermissions.htm");
}
protected void Page_Load(object sender, EventArgs e)
{
AuthorizeRequest(Response.Redirect);
}
Now the bigger problem... You do not want to do this!
Having each page assert authorization is a quick way to write security issues. Someone will forget or accidentally remove the assertion. ASP.NET has a multitude of ways to intercept and filter requests for this very purpose.
The easiest thing to do is to place this in event hooks in your Global.asax file. The HttpApplication object has several events that can be used for this purpose. Another option is to implement the IHttpModule interface. Either way, I would not write the code in each page.
Upvotes: 1
Reputation: 5914
You can make a new class, let's call it myPageClass
, that heritage from System.Web.UI.Page
, then, include all the code you need in this class make all your code behind heritable from myPageClass
.
public class myPageClass : System.Web.UI.Page
{
public void authorize()
{
// your auth code here
Response.Redirect("Invalid_Permissions_Page.aspx", false);
}
}
public partial class _Default : myPageClass
{
protected void Page_Load(object sender, EventArgs e)
{
// Your code here
}
}
In my opinion, you should not use Response.Redirect
in the cases of the action of a button, for example, if it's going to take you to another page, you don't need to go to the server to do that, that's only to be made in the client.
Upvotes: 1
Reputation: 28645
You can check the current url to make sure that it is not already the invalid permissions page before redirecting; therefore, you will only redirect when you are not already there.
if(!Request.RawUrl.Contains("Invalid Permissions Page"))
Response.Redirect("Invalid Permissions Page");
Upvotes: 3