ASP.NET Identity2 - How to get User Id with AllowA

2019-09-11 14:54发布

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);
}

1条回答
Animai°情兽
2楼-- · 2019-09-11 15:40

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

[AllowAnonymous]
[Authorize]
public IHttpActionResult GetArticle(int id)
查看更多
登录 后发表回答