Create and Use Custom Attributes

时间:2022-07-31 18:45:29

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;
        }
    }

Using in class:

[RequirePermission(")]
    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);
                    )
                    {
                        Response.Redirect(ResolveUrl("~/Error.html"));
                    }
                    else
                    {
                        RequirePermissionAttribute attribute = attributes[];
                        string moduleId = attribute.Module;
                        string function = attribute.Function;
                        //validate if has permission by module id and function
                    }

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