Redirect from Attribute
How can I create an attribute for an ASP.NET page that redirects to another page?
[MyAttribute()]
public partial class Default : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
}
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute: Attribute
{
public MyAttribute()
{
if (// something)
{
// I need to redirect to some page here
}
}
}
开发者_运维知识库
An attribute cannot redirect by itself - it is simply metadata that decorates the class/member you have defined it one.
That metadata can be used with reflection in order to perform a redirect, but you will need to put that code somewhere within the asp.net pipeline, so that the page can be inspected and a redirect can occur.
I agree with everyone else that using attributes to redirect is a weird experience.
If you really want to do this, you should look into the HttpApplication.BeginRequest event and you could probably write some code which checked each request for the page class being loaded to see if there is the attribute you want and then execute your redirection there.
Alternatively, you could probably write an abstract class which inherits from System.Web.UI.Page (all your pages in your site would need to inherit this too) and put some kind of check in the OnLoad for if the class is decorated with the attribute.
精彩评论