我有一个ASP.NET MVC 5应用程序,使用c#编写在ASP.NET MVC 5框架的顶部 .

在这个应用程序中,我使用SignalR在我的应用程序和用户的浏览器之间创建一个WebSocket连接 .

在我的SignalR中心,我希望能够访问 OwinContext 对象 .

如何从集线器访问 OwinContext 对象?

这是我试过的

Context.Request.GetHttpContext().GetOwinContext();

但是,这给了我以下错误

在上下文中找不到owin.Environment项 .

我将 <add key="owin:AutomaticAppStartup" value="true" /> 添加到了我的Web.Config文件中 .

这就是 Startup 类的样子

using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using System;

[assembly: OwinStartup(typeof(TestProject.App_Start.Startup))]
namespace TestProject.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            ConfigureAuth(app);

            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            // need to add UserManager into owin, because this is used in cookie invalidation
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = Settings.ApplicationCookie,
                LoginPath = new PathString("/Login"),
                Provider = new CookieAuthenticationProvider(),
                CookieName = Settings.ApplicationCookieName,
                CookiePath = Settings.CookiePath,
                CookieHttpOnly = true,
                SlidingExpiration = true,
                ExpireTimeSpan = TimeSpan.FromHours(24),
            });
        }
    }
}

UPDATED 案例使用说明

在某些情况下,我需要从Hub内部更新用户声明 . 这需要通知Authentication Manager有关新的声明 . 所以我使用以下方法更新ClaimsIdentity

private static void InformAuthManager(ClaimsIdentity identity, HttpContextBase context = null)
{
    IAuthenticationManager authenticationManager;

    if (context != null)
    {
        authenticationManager = context.GetOwinContext().Authentication;
    }
    else
    {
        authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
    }

    var claims = new ClaimsPrincipal(identity);
    var authProperties = new AuthenticationProperties() { IsPersistent = true };
    authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(claims, authProperties);
}