2014-04-21 124 views
4

我想在我的SignalR Hub的OnConnected方法中使用我的自定義原則。我嘗試了以下內容:SignalR Hub中的自定義原理

  • Context.Request.GetHttpContext()用戶
  • HttpContext.Current.User
  • Thread.CurrentPrincipal中

,但沒有運氣..

它一直拋出錯誤:

Unable to cast object of type 'System.Web.Security.RolePrincipal' to type 'MVCSample.Biz.Profile.MyCustomPrincipal'. 

在SignalR集線器中是否無法使用自定義原則?

謝謝!

這是我的樞紐代碼:

[Authorize] 
public class MBHub : Hub 
{ 
    private readonly ILifetimeScope _hubLifetimeScope; 
    private readonly IUserService _userService;   

    public MBHub(ILifetimeScope lifetimeScope) 
    { 
     _hubLifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest"); 
     _userService = _hubLifetimeScope.Resolve<IUserService>(); 
    } 

    public override Task OnConnected() 
    { 
     //var idn = (MVCSample.Biz.Profile.MyCustomIdentity)Thread.CurrentPrincipal; <--- THIS DID NOT WORK 

     //var idn = (MVCSample.Biz.Profile.MyCustomIdentity)HttpContext.Current.User; <--- THIS DID NOT WORK 

     System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext(); 

     var idn = (MVCSample.Biz.Profile.MyCustomIdentity)httpContext.User.Identity; // <--- THIS IS MY FINAL TRY, DID NOT WORK 

     string userName = idn.Name; 
     string city = idn.City; 
     string connectionId = Context.ConnectionId; 

     _userService.AddConnection(connectionId, userName, city, Context.Request.Headers["User-Agent"]); 

     return base.OnConnected(); 
    } 


    protected override void Dispose(bool disposing) 
    { 
     // Dipose the hub lifetime scope when the hub is disposed. 
     if (disposing && _hubLifetimeScope != null) 
      _hubLifetimeScope.Dispose(); 

     base.Dispose(disposing); 
    } 

} 
+0

'VAR myCustomPrincipal = Context.User'? –

+0

你可以分享你到目前爲止嘗試過的代碼嗎? – thepirat000

+0

請分享您的自定義身份的代碼,即'MVCSample.Biz.Profile.MyCustomIdentity' – HCJ

回答

0

你應該建立自己的授權屬性

public class MyAuthorizeAttribute : AuthorizeAttribute 
{ 
    public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) 
    { 
     //put our custom user-principal into a magic "server.User" Owin variable 
     request.Environment["server.User"] = new MyCustomPrincipal(); //<!-THIS! 

     return base.AuthorizeHubConnection(hubDescriptor, request); 
    } 
} 

,然後將該屬性應用到你的集線器。

如果你想在這個更多的信息,我的博客上講述這個here更多的代碼樣本

+0

'AuthorizeHubMethodInvocation()'永遠不會被我調用,只是在'AuthorizeHubConnection()'中設置一個主體似乎是不夠的。有任何想法嗎? – UserControl