ASP.NET Identity2-如何使用AllowAnonymous Controller获取用户ID? [英] ASP.NET Identity2 - How to get User Id with AllowAnonymous Controller?

查看:130
本文介绍了ASP.NET Identity2-如何使用AllowAnonymous Controller获取用户ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存一个数据库(日期和用户),该数据库可以查看授权和匿名用户可以访问的网页.是否有一种方法可以使两种类型的操作一起使用,因为如果该操作为[AllowAnonymous],则该用户未通过身份验证,并且我无法检索用户ID;如果该操作为[Authorize],则匿名用户无法进行此操作访问页面.

I would like to save in a database(date and user) who views a web page that can be accessed by a authorized and anonymous users. Is there a way to make an action to work with both types because if the action is [AllowAnonymous], the user is not authenticated and I can't retrieve the user id and if the action is [Authorize] the anonymous users can't access the page.

[HttpGet]
[Route("{id}/Detail")]
[AllowAnonymous]
[ResponseType(typeof(JsonArticleDetail))]
public IHttpActionResult GetArticle(int id)
{
    ...
    var entity = this.DbContext.Articles.Find(id);
    var applicationUserId = User.Identity.IsAuthenticated ? User.Identity.GetUserId() : null;

    entity.ArticleViews.Add(new ArticleView
    {
        ViewedOn = DateTime.UtcNow,
        ApplicationUserId = applicationUserId
    });

    this.DbContext.SaveChanges();
    return Ok(article);
}

推荐答案

解决方案是同时执行[AllowAnonymous][Authorize]

The solution was to have both [AllowAnonymous] and [Authorize]on the action

[AllowAnonymous]
[Authorize]
public IHttpActionResult GetArticle(int id)

这篇关于ASP.NET Identity2-如何使用AllowAnonymous Controller获取用户ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆