1

I'm trying to get username of currely logged in user by ASP.NET Generic Handler (.ashx). But the username is always nothing even though the user is currently logged in.

Here's my Generic Handler class:

Imports System.Web.SessionState

    Public Class FileUploadHandler
    Implements System.Web.IHttpHandler
    Implements IRequiresSessionState

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        'username is always null, i'm not sure why there's nothing eventhough the user is logged in     
        Dim username = context.Current.User.Identity.Name

        If String.IsNullOrEmpty(username) Then
            context.Response.StatusCode = 0
        Else
            context.Response.StatusCode = 1

        End If

    End Sub

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

But I can get the username of the logged in user from any page like this:

Dim username = Context.Current.User.Identity.Name

Do you think what it is the problem here? I'm OK with both C# and VB.NET. Thanks.

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
Narazana
  • 1,940
  • 15
  • 57
  • 88
  • 2
    Looks like a duplicate of: http://stackoverflow.com/questions/9524466/httpcontext-current-user-identity-name-not-working-in-ashx-hander – Vedran Jul 19 '12 at 09:48

2 Answers2

2

If you are using any client side component such as Uploadify, Plupload, it can be that the component is not sending authentication and session cookies with the request. There is a good explanation here for workaround.

Check out Uploadify (Session and authentication) with ASP.NET

Community
  • 1
  • 1
Tola
  • 2,401
  • 10
  • 36
  • 60
0

The default ASP.NET application built up uses cookie to authenticate users via session-id which is written in the cookie itself, while I think it should be the session object that is to deal with this. Therefore the default created MVC application is not safe to follow. you'd better change the source code into using session instead. For your issue, getting username from the user class might not be a good option as it will return an empty string. If you use session this problem will be resolved once you use the identity from the session object.

Anabella
  • 39
  • 6