我需要做一些相当简单的事情:在我的ASP.NET MVC应用程序中,我想设置一个自定义IIdentity/IPrincipal.哪个更容易/更合适.我想要扩展默认值,以便我可以调用类似User.Identity.Id和User.Identity.Role.没什么特别的,只是一些额外的属性.
我已经阅读了大量的文章和问题,但我觉得我做得比实际更难.我觉得这很容易.如果用户登录,我想设置自定义IIdentity.所以我想,我将Application_PostAuthenticateRequest在我的global.asax中实现.但是,每次请求都会调用它,并且我不希望在每个请求上调用数据库,这些请求将从数据库请求所有数据并放入自定义IPrincipal对象.这似乎也是非常不必要,缓慢,并且在错误的地方(在那里进行数据库调用)但我可能是错的.或者数据来自何处?
所以我想,每当用户登录时,我都可以在我的会话中添加一些必要的变量,我将其添加到Application_PostAuthenticateRequest事件处理程序中的自定义IIdentity中.但是,我Context.Session在null那里,所以这也不是要走的路.
我已经在这一天工作了一天,我觉得我错过了什么.这不应该太难,对吧?我也对此附带的所有(半)相关内容感到困惑.MembershipProvider,MembershipUser,RoleProvider,ProfileProvider,IPrincipal,IIdentity,FormsAuthentication....我是唯一一个谁发现这一切非常混乱?
如果有人能告诉我一个简单,优雅,高效的解决方案,可以在IIdentity上存储一些额外的数据而不需要额外的模糊...这将是非常棒的!我知道在SO上有类似的问题,但如果我需要的答案就在那里,我一定会忽略.
asp.net asp.net-mvc forms-authentication iprincipal iidentity
我通过在ApplicationUser派生自的类中添加几个字段来扩展ASP NET标识架构IdentityUser.我添加的领域之一是FullName.
现在,当我写的时候User.Identity.Name,它给了我用户名,我正在寻找类似的东西User.Identity.FullName应该返回我添加的FullName.
不确定,如何实现这一点,我们将非常感谢任何指导.
谢谢.
设置(使用MVC 4)
public class MyAuthorizeAttribute : AuthorizeAttribute {
protected override bool AuthorizeCore(HttpContextBase httpContext) {
var isAuthorised = base.AuthorizeCore(httpContext);
if(isAuthorised) {
// retrieve authentication ticket from cookie and
// create custome principal and attach to
// httpContext.User
}
return isAuthorised;
}
}
Run Code Online (Sandbox Code Playgroud)
Gloabl.asax.cs:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new MyAuthorizeAttribute());
}
Run Code Online (Sandbox Code Playgroud)
HomeController.cs:
using System.Web.Mvc;
public class HomeController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
问题
对主页的调用会强制加载登录页面.
题
当HomeController.Index()动作用[AllowAnonymous]修饰时,为什么ASP会将我重定向到登录视图?
我正在使用这篇文章作为参考
asp.net security authentication asp.net-mvc forms-authentication