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);
}
The solution was to have both
[AllowAnonymous]
and[Authorize]
on the action