ASP.NET中的自定义角色

编程入门 行业动态 更新时间:2024-10-26 08:29:10
本文介绍了ASP.NET中的自定义角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在一个ASP.NET网站,该网站使用窗体身份验证使用自定义的验证机制(它设置在 e.Authenticated 编程上保护无效Login_Authenticate(对象发件人,AuthenticateEventArgs E))。

I am working on an ASP.NET website which uses forms authentication with a custom authentication mechanism (which sets e.Authenticated programmatically on protected void Login_Authenticate(object sender, AuthenticateEventArgs e)).

我有一个ASP.NET站点地图。有些元素必须显示只有登录用户。其他必须显示只有一个,唯一的用户(即管理员,这永远不会改变用户名标识)。

I have an ASP.NET sitemap. Some elements must be displayed only to logged in users. Others must be displayed only to one, unique user (ie. administrator, identified by a user name which will never change).

我想避免什么:

  • 设置自定义角色提供:太多了code为这样一个基本的东西写,
  • 通过删除网站地图,并以$ C $替换它的c-背后的解决方案改造现有code为例。

我想要做的:

  • 纯code隐藏解决方案,这将让我分配上进行身份验证事件的作用。

这可能吗?怎么样?如果没有,是否有一个易于-DO解决方法吗?

Is it possible? How? If not, is there an easy-to-do workaround?

推荐答案

至于马太说,建设主体,并在适当的时候自己设定它采取一切内置的基于角色的好东西像网站地图的优势,最简单的方法

As Matthew says, building a principal and setting it yourself at the right moment is the easiest way to take advantage of all of the built in Role based goodies like SiteMap.

但是,实施这一比MSDN所示的要容易得多基于标准的方法。

But there is a much easier standards based method of implementing this than shown by MSDN.

这是我如何实现一个简单的角色提供

This is how I implement a simple role provider

Global.asax中

Global.asax

using System; using System.Collections.Specialized; using System.Security.Principal; using System.Threading; using System.Web; using System.Web.Security; namespace SimpleRoles { public class Global : HttpApplication { private static readonly NameValueCollection Roles = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase) { {"administrator", "admins"}, // note, a user can be in more than one role {"administrator", "codePoets"}, }; protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); Context.User = Thread.CurrentPrincipal = new GenericPrincipal(Context.User.Identity, Roles.GetValues(ticket.Name)); } } } }

要手动检查用户在一个页面codebehind的背景:

To manually check the user in the context of a Page codebehind:

if (User.IsInRole("admins")) { // allow something }

在其他地方刚刚得到的用户从当前上下文的

Elsewhere just get the user off of the current context

if (HttpContext.Current.User.IsInRole("admins")) { // allow something }

更多推荐

ASP.NET中的自定义角色

本文发布于:2023-11-14 14:50:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   角色   ASP   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!