signalr Hub中Context的User爲Null

1.問題

signalr無法判斷某次連接是哪個用戶,在Context中查看User對象爲null
在這裏插入圖片描述

2.解決

在start_up中加入 ConfigureAuth(app); 跟app.MapSignalR()一起;
在這裏插入圖片描述
其中我的ConfigureAuth方法如下(用的是Microsoft.AspNet.Identity中的登錄、用戶管理、用戶權限等功能,如果不懂可以查找相關資料):

using BE.Common;
using BE.EF;
using BLL.GlobalMethod;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Microsoft.Owin.Security.DataHandler.Serializer;
using Microsoft.Owin.Security.DataProtection;
using Owin;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace JGHPCX.App_Start
{
    public partial class Startup
    {
        public static IDataProtector dataProtector = null;

        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // 配置數據庫上下文、用戶管理器和登錄管理器,以便爲每個請求使用單個實例
            app.CreatePerOwinContext(DBModel.Create);
            app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext<AppSignInManager>(AppSignInManager.Create);
            app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);

             
            // 使應用程序可以使用 Cookie 來存儲已登錄用戶的信息
            // 並使用 Cookie 來臨時存儲有關使用第三方登錄提供程序登錄的用戶的信息
            // 配置登錄 Cookie
            var options = new CookieAuthenticationOptions
            {
                AuthenticationType = CustomAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Login/LoginPage"),
                Provider = new CookieAuthenticationProvider
                {
                    // 當用戶登錄時使應用程序可以驗證安全戳。
                    // 這是一項安全功能,當你更改密碼或者向帳戶添加外部登錄名時,將使用此功能。
                    //OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<AppUserManager, User>(
                    //    validateInterval: TimeSpan.FromMinutes(30),
                    //    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            };
            app.UseCookieAuthentication(options);
            app.UseExternalSignInCookie(CustomAuthenticationTypes.ExternalCookie);

            // 使應用程序可以在雙重身份驗證過程中驗證第二因素時暫時存儲用戶信息。
            app.UseTwoFactorSignInCookie(CustomAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // 使應用程序可以記住第二登錄驗證因素,例如電話或電子郵件。
            // 選中此選項後,登錄過程中執行的第二個驗證步驟將保存到你登錄時所在的設備上。
            // 此選項類似於在登錄時提供的“記住我”選項。
            app.UseTwoFactorRememberBrowserCookie(CustomAuthenticationTypes.TwoFactorRememberBrowserCookie);

       
        }

       
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章