[SOLVED] ASP.NET Identity2 – How to get User Id with AllowAnonymous Controller?

Issue

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

Solution

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

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

Answered By – Pavel

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *