64

how can i check if a user is logged in in user control with asp.net mvc

usually on a view page i use this

<% if (User.Identity.IsAuthenticated) {%>
  //Do something
<% } %>

but i can't get this done on a user control

4 Answers 4

77

Does this work?

<%= Page.User.Identity.IsAuthenticated %>
1
  • 8
    Or try <%= Context.User.Identity.IsAuthenticated %>
    – Jo Smo
    May 4, 2015 at 22:45
73

Nothing new to add to Griegs answer, but I would normally do

@Request.IsAuthenticated
3
  • 3
    Looking at the reference sources for HttpRequestWrapper and then HttpRequest the IsAuthenticated property is implemented with User.Identity.IsAuthenticated, among other things. return(_context.User != null && _context.User.Identity != null && _context.User.Identity.IsAuthenticated); Jul 7, 2013 at 8:18
  • 1
    So what's the difference? Or are these two identical?
    – Jo Smo
    Jan 9, 2016 at 16:06
  • Pretty much. Mine is shorter. :-) Jan 10, 2016 at 0:07
9

You could decorate the Method with the Authorize attribute. This requires that the User calling the Method being authenticated.

0

Well I use VB

If User.Identity.Name = "" Then
   Response.Redirect("~/Login.aspx")
Else
   ........continue...........
End If
1
  • As the original question did not have access to User, how would this make any difference "in a user control". Your example is in a controller and not a user-control. -1 Jul 24, 2015 at 11:40

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.