'ASP.NET Identity2 - How to get User Id with AllowAnonymous Controller?
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
