Create and Use Custom Attributes

http://www.codeproject.com/Articles/1811/Creating-and-Using-Attributes-in-your-NET-applicat

 

Create a custom attribute class:

[AttributeUsage(AttributeTargets.Class)] // this attribute can only be used by class

public class RequirePermissionAttribute : Attribute
    {
        public string Module { get; set; }

        public string Function { get; set; }

        public RequirePermissionAttribute(string moduleId, string function)
        {
            if(string.IsNullOrEmpty(moduleId))
                throw new ArgumentException("'Module' cannot be empty.", "Module");

            this.Module = moduleId;
            this.Function = function;
        }
    }
View Code

 

Using in class:

[RequirePermission("1", "2")]
    public partial class WebForm2 : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }

 

How to use in BasePage.cs

RequirePermissionAttribute[] attributes = (RequirePermissionAttribute[])Page.GetType().GetCustomAttributes(typeof(RequirePermissionAttribute), true);
                    if (attributes.Length == 0)
                    {
                        Response.Redirect(ResolveUrl("~/Error.html"));
                    }
                    else
                    {
                        RequirePermissionAttribute attribute = attributes[0];
                        string moduleId = attribute.Module;
                        string function = attribute.Function;
                        //validate if has permission by module id and function
                    }
View Code

 

 

request.UrlReferrer

INPUT

Response.Write("<br/> " + HttpContext.Current.Request.Url.Host); Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority); Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath); Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath); Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri); Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);

OUTPUT

localhost localhost:60527 /WebSite1test/Default2.aspx /WebSite1test http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2 /WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2

你可能感兴趣的:(Create and Use Custom Attributes)