![](/img/trans.png)
[英]SignalR Hub broadcasting from custom function triggered by Hub method
[英]Custom principle in SignalR Hub
我正在嘗試在SignalR Hub的OnConnected方法中使用我的自定義原則。 我嘗試了以下方法:
但沒有運氣..
它不斷拋出錯誤:
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);
}
}
您應該構建自己的Authorize屬性
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);
}
}
然后將此屬性應用於您的Hub。
如果你想了解更多這方面的信息,我在這里寫了更多代碼示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.