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

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112

4 Answers4

77

Does this work?

<%= Page.User.Identity.IsAuthenticated %>
griegs
  • 22,624
  • 33
  • 128
  • 205
73

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

@Request.IsAuthenticated
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
  • 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);` – ta.speot.is Jul 07 '13 at 08:18
  • 1
    So what's the difference? Or are these two identical? – Jo Smo Jan 09 '16 at 16:06
  • Pretty much. Mine is shorter. :-) – Dan Atkinson Jan 10 '16 at 00:07
9

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

CmdrTallen
  • 2,264
  • 4
  • 28
  • 50
0

Well I use VB

If User.Identity.Name = "" Then
   Response.Redirect("~/Login.aspx")
Else
   ........continue...........
End If
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Eshan
  • 17
  • 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 – iCollect.it Ltd Jul 24 '15 at 11:40