gpt4 book ai didi

c# - SignalR Hub 中的自定义原则

转载 作者:行者123 更新时间:2023-11-30 12:59:59 26 4
gpt4 key购买 nike

我正在尝试在我的 SignalR Hub 的 OnConnected 方法中使用我的自定义原则。我尝试了以下方法:

  • Context.Request.GetHttpContext().User
  • 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);
}

}

最佳答案

您应该构建自己的授权属性

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。

如果您想了解更多信息,我写了关于此的博客 here更多代码示例

关于c# - SignalR Hub 中的自定义原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23207607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com