您还应该注意 .net 4.5 声明主体方法。WindowsIdentity.GetCurrent().Name;
我在 VS2012 上使用 EF5.0 目标 .net4.5 目标 .net4.5 测试和 之间的区别 Thread.CurrentPrincipal
我在 Forms auth 下使用了一个像这样的小程序。所以 Windows Auth 和 Forms Auth 可以一起玩。
不是完全相同的情况,但它确实突出了当一切正常时被忽略的重要区别。
值得快速阅读... http://msdn.microsoft.com/en-us/library/system.security.claims.claimsprincipal.current
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace BosIdentityManager
{
public class BosPrincipal
{
/// <summary>
/// The current principal is set during FORMS authentication. If WINDOWS auth mode is in use, Windows sets it.
/// </summary>
/// <returns> The Name from Thread.CurrentPrincipal.Identity.Name unless alternate delegate is configured</returns>
public static string GetCurrentUserName()
{
// http://msdn.microsoft.com/en-us/library/system.security.claims.claimsprincipal.current
// with forms auth and windows integrated,ClaimsPrincipal.Current will be set.
var prin = ClaimsPrincipal.Current; //normally this reverts to Thread.CurrentPrincipal, but can chnage !
return prin.Identity.Name;
}
public static string GetCurrentWindowsUserName()
{
return WindowsIdentity.GetCurrent().Name;
}
public static void SetPrincipal(BosMasterModel.Membership memb)
{
var claims = new List<Claim>(){ new Claim(ClaimTypes.Name, memb.SystemUser.UserName),
new Claim(ClaimTypes.NameIdentifier,memb.UserId.ToString()),
new Claim(ClaimTypes.Role, "SystemUser") };
var ClaimsId = new ClaimsIdentity(claims,"Forms");
var prin = new ClaimsPrincipal(ClaimsId);
Thread.CurrentPrincipal = prin;
}
}
}