我正在尝试将HttpContext.Current.User.Identity中的IIdentity绑定到自定义IPrincipal,但从我收集的信息来看,在对用户进行身份验证之前,IIdentity为空。
示例代码:
public interface ICustomPrincipal
{
int UserID { get; set; }
}
public class CustomPrincipal : ICustomPrincipal
{
private readonly IIdentity _identity;
private readonly IUserRepository _userRepository;
public CustomPrincipal(IIdentity identity, IUserRepository repository)
{
_identity = identity;
_repository = repository;
}
}然后
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (Request.IsAuthenticated && !Request.Url.AbsoluteUri.Contains(".axd"))
{
HttpContext.Current.User as CustomPrincipal;
}
}我可以绑定IUserRepository没有问题,但我不知道如何正确绑定IIdentity。
我尝试在Application_Start上的CreateKernel()中绑定HttpContext.Current.User.Identity,但问题是,IIdentity为空。
我也尝试过使用GlobalFilters和Ninject.BindFilter方法来设置CustomPrincipal,但问题又回到了IIdentity为空的问题上。
我不想调用CustomPrincipal的构造函数,因为IUserRepository也涉及构造函数注入。
我不确定我的绑定是否正确,或者我的实现方法不正确,任何想法或建议都将不胜感激。
我最终想要实现的是将ICustomPrincipal向下传递到DB级别,以记录事务的UserID。
谢谢
发布于 2013-06-04 07:08:01
下面的示例显示了身份验证前后的引导程序
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//WebApiConfig.Register(GlobalConfiguration.Configuration);
//BundleMobileConfig.RegisterBundles(BundleTable.Bundles);
}
private bool _isBootStrapped;
private bool _isBootStrappedAuthenticated;
public override void Init()
{
base.Init();
// handlers managed by ASP.Net during Forms authentication
BeginRequest += new EventHandler(BeginRequestHandler);
PostAuthorizeRequest += new EventHandler(PostAuthHandler);
EndRequest += new EventHandler(EndRequestHandler);
}
public void EndRequestHandler(object sender, EventArgs e)
{
}
public void BeginRequestHandler(object sender, EventArgs e)
{
BootStrapUnauthentiated();
}
public void PostAuthHandler(object sender, EventArgs e)
{
if (_isBootStrappedAuthenticated)
{
return; // nuff done...
}
BootStrapAuthenticated();
BootStrapUnauthentiated();
}
private void BootStrapAuthenticated()
{
if (Request.IsAuthenticated)
{
BootStrapHttp(Context);
BootStrapper.RegisterInfrastureAdapters();
_isBootStrapped = true;
_isBootStrappedAuthenticated = true;
}
}
private void BootStrapUnauthentiated()
{
if (!_isBootStrapped)
{ // minimal bootstrap for launch but user not yet known, eg logon screen
BootStrapHttp(Context);
BootStrapper.RegisterInfrastureAdapters();
_isBootStrapped = true; // just a connection, if no persisted cookie, the may not be authenticated yet
}
}
}https://stackoverflow.com/questions/16888081
复制相似问题