ASP.NET Identity2 - How to get User Id with AllowAnonymous Controller?

青春壹個敷衍的年華 提交于 2019-12-12 00:32:32

问题


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:


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

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


来源:https://stackoverflow.com/questions/32411757/asp-net-identity2-how-to-get-user-id-with-allowanonymous-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!