コード例 #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSession();
            app.UseStatusCodePages();
            app.UseDeveloperExceptionPage();
            app.UseRouting();
            app.Use(async(context, next) => {
                Type type         = default;
                MethodInfo method = default;
                try{
                    type   = Type.GetType($"DatabaseDevelopment.Controllers.{context.Request.RouteValues["controller"].ToString()}Controller");
                    method = type.GetMethods().Where(x => x.Name == $"{context.Request.RouteValues["action"].ToString()}").First();
                }
                catch (NullReferenceException) {
                    context.Response.StatusCode = 404;
                    return;
                }
                //Обработка атрибута HasRole
                if (method.HasAttribute(typeof(HasRole)))
                {
                    bool isValid = true;
                    var user     = new SessionHelper <User>(context.Session)["user"];
                    IEnumerable <bool> Validates = new List <bool>();
                    foreach (var attr in method.GetCustomAttributes(typeof(HasRole), false))
                    {
                        if ((attr is null) || (!(attr as HasRole).IsValid(user, "admin")))
                        {
                            isValid = false;
                        }

                        else
                        {
                            Validates.Append(true);
                        }
                    }
                    if (!isValid || method.GetCustomAttributes(false).Length == Validates.Count())
                    {
                        context.Response.StatusCode = 404;
                        return;
                    }
                }