Null exception on HttpContext.Current.Request.Cook

2019-07-06 05:41发布

问题:

I'm having an odd issue that I cannot seem to figure out or even understand properly.

Basically I have a basic Authorisation method that fetches a security token (cookie) and compares it to the currently logged on user. When firing this from a SignalR method it throws a null exception but I know the user has security token. This works fine without SignalR.

I'll provide code etc..To help understand the problem.

The Architecture:

  1. Business Layer
  2. Presentation Layer

//Located within the business layer
public static User getUserBySecurityToken()
{
   string securityToken = "";
   if (HttpContext.Current.Request.Cookies["SecurityToken"] != null)
   {
     securityToken = HttpContext.Current.Request.Cookies["SecurityToken"].Value.ToString();                                                   
   } 

   return user;
}

//Located within the presentation layer (hubs)
public void Arrange(int tid, string status, string content) 
{
     //Get logged on user
    Business.User user = Business.User.getUserBySecurityToken();
    if (user != null)
    {
        Clients.Group(user.campaignName).changeTicket(tid, status, content);
    }

}

//Located within the presentation layer (client side script)
$(document).on('click', '.move-option-js', function (e) {
    //This does not even get called due to cookie being null
    window.hubReady.done(function ()
    {
        panelHub.server.arrange(i, s, content);
    });
});

Please note I have omitted some code for the readability. I hope I could get a better understanding of this problem and maybe slightly re-factor the code to get it working.

EDITS

After more testing all is fine and works perfect the first time but thereafter it fails.

回答1:

To the best of my knowledge the issue was SingalR running in it's own thread and my SecurityToken Method runs in the main thread. So after the first page load the main thread no longer exists, So you have to program within the SignalR Context.

I fixed the issue by overloading my original method and passing in a SignalR Context Cookie Request. Code Below:

The works from a class that inherits from the Hub.

Context.RequestCookies["SecurityToken"].Value.ToString()

Hope this helps future readers.

Regards,



标签: c# signalr