0

何时调用方法 SignIn 我收到错误 NullReferenceExepction。

这是我的视图模型:

public Masterpage1ViewModel() {
        UserIdentity user = new UserIdentity("Admin");
        var claimsIdentity = new ClaimsIdentity(user);

        Context.OwinContext.Authentication.SignIn(claimsIdentity);
  }

这是 UserIdentity 的类:

public class UserIdentity : IIdentity
{
    public string AuthenticationType
    {
        get { return DefaultAuthenticationTypes.ApplicationCookie; }
    }

    public bool IsAuthenticated { get; set; }

    public string Name { get; private set; }

    public UserIdentity(string name)
    {
        Name = name;
    }
}

我还添加到 Startup.cs:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            Provider = new CookieAuthenticationProvider()
            {
                OnApplyRedirect = e => DotvvmAuthenticationHelper.ApplyRedirectResponse(e.OwinContext, e.RedirectUri)
            }
        });
4

1 回答 1

0

看起来ClaimsIdentity未正确初始化,可能与UserIdentityOWIN Cookie 安全中间件内部某处的崩溃相结合。

我们使用下面的代码来初始化它:

var identity = new ClaimsIdentity(new[]
{
    new Claim(ClaimTypes.Name, UserName),
    // add another claims (e.g. for each role)
},
CookieAuthenticationDefaults.AuthenticationType);
Context.OwinContext.Authentication.SignIn(identity);
于 2016-09-08T08:55:58.687 回答