csharp ASP .NET授权模块,用于从呈现的页面中删除不可访问的控件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp ASP .NET授权模块,用于从呈现的页面中删除不可访问的控件相关的知识,希望对你有一定的参考价值。

using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AuthorizationTest.HttpModules
{
    public class AuthorizationModule : IHttpModule
    {
        private HttpApplication application;

        public void Init(HttpApplication context)
        {
            application = context;

            application.PostMapRequestHandler += HttpApplication_PostMapRequestHandler;
        }

        public void Dispose()
        {
            application.PostMapRequestHandler -= HttpApplication_PostMapRequestHandler;
        }

        private void HttpApplication_PostMapRequestHandler(object sender, EventArgs e)
        {
            var page = application.Context.Handler as Page;
            if (page == null)
                return;
            page.PreRender += new EventHandler(Page_PreRender);
        }

        private void Page_PreRender(object sender, EventArgs e)
        {
            var page = sender as Page;
            var sw = System.Diagnostics.Stopwatch.StartNew();
            EnforceAuthorization(page.Controls);
            System.Diagnostics.Trace.WriteLine(sw.ElapsedMilliseconds);
            page.PreRender -= Page_PreRender;
        }
        
        private void EnforceAuthorization(ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                var webControl = control as WebControl;
                if (webControl != null)
                {
                    var feature = webControl.Attributes["feature"];
                    if (feature != null)
                    {
                        webControl.Visible = HasFeature(feature);

                        webControl.Attributes.Remove("feature");
                    }
                }

                EnforceAuthorization(control.Controls);
            }
        }

        private bool HasFeature(string feature)
        {
            var features = new[] { "Foo", "Bar" };
            return features.Contains(feature);
        }
    }
}

以上是关于csharp ASP .NET授权模块,用于从呈现的页面中删除不可访问的控件的主要内容,如果未能解决你的问题,请参考以下文章

csharp 用于ASP.NET MVC的Ajax ActionFilter

csharp 用于处理DataTables.net客户端表呈现插件的Ajax调用的C#代码。

csharp 用于ASP.NET MVC的Castle Windsor IoC容器设置

关于 ASP.NET Core 中的授权

ASP .NET MVC 中的 Authorize 属性是不是用于身份验证和授权?

csharp 从ASP.NET WebAPI控制器以camelCase格式返回JSON数据。