【问题标题】:Why is Context.User.Identity.Name always empty?为什么 Context.User.Identity.Name 总是空的?
【发布时间】:2016-11-01 20:14:46
【问题描述】:

Context.User.Identity.Name 一直为空,目前我正在使用 WebForms:

HttpCookie cookie = new HttpCookie("jamal");
cookie.Value = "bilal";
HttpContext.Current.Response.Cookies.Add(cookie);

这里我要用户名:

public override Task OnConnected()
{
    AddUser(Context.User.Identity.Name, this.Context.ConnectionId);
}

private static void AddUser(String username, String connectionId)
{
    ISet<String> connections;

    if (users.TryGetValue(username, out connections) == false)
    {
        connections = users[username] = new HashSet<String>();
    }

    connections.Add(connectionId);
}

【问题讨论】:

  • 你在哪里打电话给Context.User.Identity.Name?另外,用户是否经过身份验证?

标签: c# webforms httpcontext


【解决方案1】:

发生这种情况是因为您没有要求对此操作进行身份验证。
要求用户通过使用Authorize 属性类装饰来授权该操作 - 这将启动身份验证协商。 我从未尝试过使用 webform,但如果您在 web 配置中添加此规则,它应该可以工作:

<authentication mode="Forms" />

【讨论】:

【解决方案2】:

尝试在 Page_Load 事件上调用它,你可能调用得太早了。

【讨论】:

    【解决方案3】:

    您创建 cookie 的方式不是身份验证 cookie。如果您创建一个新的 asp.net Web 表单项目,Asp.net 会为您处理身份验证过程。但是,如果您想创建自己的身份验证 cookie,则必须遵循 these are the steps。

    来自 asp.net 的FormsAuthenticationModule 通过检查身份验证票来对用户进行身份验证。您的 cookie 只有一个名称。您必须创建票证。 Also check this link.

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 1970-01-01
      • 2020-07-20
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多