加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 使用Azure redis.cache跨负载均衡服务存储MVC应用程

发布时间:2020-12-16 09:54:33 所属栏目:asp.Net 来源:网络整理
导读:我有一个Azure PaaS,我想为高可用性配置,我已经为实例添加了另一个角色,现在我需要配置ASP.Net会话以存储在分布式缓存中.我找到了有关如何使用缓存的以下信息: http://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-red
我有一个Azure PaaS,我想为高可用性配置,我已经为实例添加了另一个角色,现在我需要配置ASP.Net会话以存储在分布式缓存中.我找到了有关如何使用缓存的以下信息:

http://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/#store-session

我已登录Azure并创建了预览缓存.我添加了StackExchange.Redis nuget包和RedisSessionStateProvider nuget,我的web配置现在看起来如下:

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,EntityFramework,Version=6.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection,System.IdentityModel,Version=4.0.0.0,PublicKeyToken=B77A5C561934E089" />
    <section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection,System.IdentityModel.Services,PublicKeyToken=B77A5C561934E089" />    
  </configSections>

  <connectionStrings>
    <add name="MetaLearningContext" connectionString="Data Source=server.database.windows.net;Initial Catalog=databasename;User ID=admin@server;Password=password;" providerName="System.Data.SqlClient" />    
  </connectionStrings>

  <appSettings>
  .................
  </appSettings>

  <location path="FederationMetadata">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>      
      <sessionState mode="Custom" customProvider="MySessionStateStore">
        <providers>
          <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="metalearningdev.redis.cache.windows.net" port="6380" accessKey="accesskeyhere" ssl="true" />
        </providers>
      </sessionState>
    </system.web>
  </location>

在我获取登录用户的用户名的方法中,我调用了以下方法,缓存中有两个get和两个set,但是查看门户日志我看不到任何调用:

public static void GetUserName()
    {
        ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("metalearningdev.redis.cache.windows.net,ssl=true,password=passwrod");

        // connection referes to a previously configured ConnectionMultiplexer
        IDatabase cache = connection.GetDatabase();

        // Perform cache operations using the cache object...
        // Simple put of integral data types into the cache
        cache.StringSet("key1","value");
        cache.StringSet("key2",25);

        // Simple get of data types from the cache
        string key1 = cache.StringGet("key1");
        int key2 = (int)cache.StringGet("key2");

        string userName = "";
        string domainStub = "";
        bool updatedLogin = false;
        string loginTime = "";
        //if (System.Configuration.ConfigurationManager.AppSettings["authenticationType"].ToString() == "ADFS")            
        if (System.Configuration.ConfigurationManager.AppSettings["platformType"].ToString() == "Cloud")    
        {
          //string userName = "";
          System.Security.Claims.ClaimsIdentity claimsIdentity = (System.Security.Claims.ClaimsIdentity)System.Threading.Thread.CurrentPrincipal.Identity;

          foreach (System.Security.Claims.Claim claim in claimsIdentity.Claims)
          {
              if (claim.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname")
              {
                  userName = claim.Value;
              }
              else if(claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")
              {
                  userName = HttpContext.Current.User.Identity.Name;
                  domainStub = "FORMS";
              }
              else if (claim.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant")
              {
                  loginTime = claim.Value;
                  updatedLogin = true;
              }
          }

          if (userName.Contains(""))
          {
            string[] stringArray = userName.Split(new Char[] { '' });
            domainStub = stringArray[0];
            userName = stringArray[1];
          }              
          HttpContext.Current.Session["domainStub"] = domainStub;
          HttpContext.Current.Session["userName"] = userName;
          HttpContext.Current.Session["updatedLogin"] = updatedLogin;
          HttpContext.Current.Session["loginTime"] = loginTime;
          HttpContext.Current.Session["companyName"] = System.Configuration.ConfigurationManager.AppSettings["companyName"].ToString();
          //HttpContext.Current.Session["companyName"] = System.Configuration.ConfigurationManager.AppSettings["companyName"].ToString();
        }            
        else if (System.Configuration.ConfigurationManager.AppSettings["platformType"].ToString() == "internal")
        {
            userName = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
            if (userName.Contains(""))
            {
                string[] stringArray = userName.Split(new Char[] { '' });
                domainStub = stringArray[0];
                userName = stringArray[1];
            }
            HttpContext.Current.Session["domainStub"] = domainStub;
            HttpContext.Current.Session["userName"] = userName;
            HttpContext.Current.Session["companyName"] = System.Configuration.ConfigurationManager.AppSettings["companyName"].ToString();
        }
    }

任何人都可以看到我做错了什么才能将会话保存到缓存中?

解决方法

您可以使用Redis的CLI(命令行界面)并连接到远程redis服务器:

Connecting to remote redis server

然后,您可以“获取”密钥的值并检查它是否已设置.

您可以在此处下载CLI for Windows:

https://github.com/MSOpenTech/redis

对于Linux / Mac Os,您可以使用apt-get / wget

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读