Azure角色缓存无法在服务器上启动“未在托管服务或开发结构中运行”。

时间:2014-06-08 00:06:50

标签: asp.net-mvc-4 azure azure-caching azure-in-role-cache

我开始使用Azure角色内缓存,一切都在本地计算机上的Azure计算模拟器中运行良好,但在服务器上运行不正常。我已经解决了一些问题,比如服务器上缺少msshrtmi.dll,但现在无法理解为什么会出现这个错误:

Not running in a hosted service or the Development Fabric. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.InvalidOperationException: Not running in a hosted service or the Development Fabric.

Source Error: 


 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 



[InvalidOperationException: Not running in a hosted service or the Development Fabric.]
   Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitor.GetDefaultStartupInfoForCurrentRoleInstance() +535
   Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener..ctor() +34

[ConfigurationErrorsException: Could not create Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.]
   System.Diagnostics.TraceUtils.GetRuntimeObject(String className, Type baseType, String initializeData) +1588
   System.Diagnostics.TypedElement.BaseGetRuntimeObject() +103
   System.Diagnostics.ListenerElement.GetRuntimeObject() +825
   System.Diagnostics.ListenerElementsCollection.GetRuntimeObject() +261
   System.Diagnostics.TraceInternal.get_Listeners() +256
   System.Diagnostics.Trace.get_Listeners() +79
   Microsoft.ApplicationServer.Caching.DataCacheServerLogManager..cctor() +97

[TypeInitializationException: The type initializer for 'Microsoft.ApplicationServer.Caching.DataCacheServerLogManager' threw an exception.]
   Microsoft.ApplicationServer.Caching.DataCacheServerLogManager.ChangeLogLevel(TraceLevel traceLevel) +0
   Microsoft.ApplicationServer.Caching.ServiceConfigurationManager..cctor() +24

[TypeInitializationException: The type initializer for 'Microsoft.ApplicationServer.Caching.ServiceConfigurationManager' threw an exception.]
   Microsoft.ApplicationServer.Caching.ServiceConfigurationManager.GetHostDefaults() +0
   Microsoft.ApplicationServer.Caching.OMCacheNodeProperties..ctor(IHostConfiguration props, Int32 maxNC, Boolean perfCounterRequired) +69
   Microsoft.ApplicationServer.Caching.LocalCacheStore..ctor(EvictionParametrs evictionParams) +50
   Microsoft.ApplicationServer.Caching.DataCacheFactory..ctor(DataCacheFactoryConfiguration configuration) +555
   Microsoft.Web.DistributedCache.DataCacheFactoryWrapper.CreateDataCacheFactoryFromConfiguration(DataCacheFactoryConfiguration config) +35
   Microsoft.Web.DistributedCache.CacheHelpers.RunCacheCreationHooks(CacheConnectingEventArgs fetchingEventArgs, IDataCacheFactory dataCacheFactory, Object sender, EventHandler`1 fetchingHandler, EventHandler`1 fetchedHandler) +70
   Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.CreateInternalProvider(IHttpRuntime httpRuntime, OutputCacheInitializationData initData, IDataCacheFactory dataCacheFactory, EventHandler`1 cacheFetching, EventHandler`1 cacheFetched) +123
   Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.GetInternalProvider() +224
   Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.Get(String key) +13
   System.Web.Caching.OutputCache.Get(String key) +80
   System.Web.Caching.OutputCacheModule.OnEnter(Object source, EventArgs eventArgs) +321
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +182
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165

我发现有关此错误的所有内容是,如果您使用角色内缓存启动本地Azure计算模拟器并且没有管理权限,则会发生此错误。但是在模拟器中一切正常,只有在我发布到登台环境后才会出现问题。 (如果切换到生产,错误仍然存​​在)。

我使用缓存来解析/ username和/ countryname等路由。因此可用的用户名和国家/地区名称将被缓存并更新数据库中的更改。我有静态类和静态DataCache对象,它是在第一次缓存请求时创建的。但是在我尝试创建缓存对象之前,即使主页也没有启动,因此发生错误。

Web.Config中。我是否从web.config中删除了所有与缓存和缓存诊断相关的配置,应用程序启动。

<configuration>
  <configSections>     
    <section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" />
  <section name="cacheDiagnostics" type="Microsoft.ApplicationServer.Caching.AzureCommon.DiagnosticsConfigurationSection, Microsoft.ApplicationServer.Caching.AzureCommon" allowLocation="true" allowDefinition="Everywhere" /></configSections>
  <system.diagnostics>
    <trace>
      <listeners>
        <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics" />
      </listeners>
    </trace>
  </system.diagnostics>
  <system.data>
    <DbProviderFactories>
      <add name="Sql Azure Reliable Provider" invariant="ReliableDbProvider.SqlAzure" description="Reliable Db Provider for SQL Azure" type="ReliableDbProvider.SqlAzure.SqlAzureProvider, ReliableDbProvider" />
      <add name="Sql Azure Reliable Provider With Timeout Retries" invariant="ReliableDbProvider.SqlAzureWithTimeoutRetries" description="Reliable Db Provider for SQL Azure with Timeout Retries" type="ReliableDbProvider.SqlAzureWithTimeoutRetries.SqlAzureProvider, ReliableDbProvider" />
    </DbProviderFactories>
  </system.data>
  <connectionStrings>
    <add name="AppDB" connectionString="value" />
    <add name="StorageConnectionString" connectionString="value" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <!--
    For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.

    The following attributes can be set on the <httpRuntime> tag.
      <system.Web>
        <httpRuntime targetFramework="4.5" />
      </system.Web>
  -->
  <system.web>
    <customErrors mode="Off" />
    <roleManager enabled="true" defaultProvider="provider">
      <providers>
        <clear />
        <remove name="AspNetSqlRoleProvider" />
        <add name="name" type="type" />
      </providers>
    </roleManager>
    <membership defaultProvider="provider">
      <providers>
        <clear />
        <remove name="AspNetSqlMembershipProvider" />
        <add name="name" type="type" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="name" />
      </providers>
    </membership>
    <machineKey validationKey="key" decryptionKey="key" validation="SHA1" decryption="AES" />
    <httpCookies httpOnlyCookies="true" requireSSL="false" />
    <authentication mode="Forms">
      <forms loginUrl="~/account/logon" protection="All" path="/" enableCrossAppRedirects="true" timeout="2880" />
    </authentication>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <pages controlRenderingCompatibilityVersion="4.0">
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
        <add namespace="System.Web.Optimization" />
      </namespaces>
    </pages>
    <httpRuntime maxRequestLength="1048576" />
    <globalization enableClientBasedCulture="true" uiCulture="auto" culture="auto" />
  <!-- Windows Azure Cache session state provider --><!--<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
      <providers>
        <add name="AFCacheSessionStateProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheSessionState"/>
      </providers>
    </sessionState>--><!-- Windows Azure Cache output cache provider --><!--Uncomment this section to use Windows Azure Cache for output cache-->
    <caching>
      <outputCache defaultProvider="AFCacheOutputCacheProvider">
        <providers>
          <add name="AFCacheOutputCacheProvider" type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheOutputCache" />
        </providers>
      </outputCache>
    </caching>
  </system.web>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
    </staticContent>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="false" />
    <directoryBrowse enabled="false" />
    <httpProtocol>
      <customHeaders>
        <!-- Enable Cross Domain AJAX calls -->
        <remove name="Access-Control-Allow-Origin" />
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
    <handlers>
      <add name="UrlRoutingHandler" type="System.Web.Routing.UrlRoutingHandler,                   System.Web, Version=4.0.0.0,                   Culture=neutral,                   PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
      <add name="UrlRoutingHandlerEmailLogo" type="System.Web.Routing.UrlRoutingHandler,System.Web, Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
      <add name="UrlRoutingHandlerSitemap" type="System.Web.Routing.UrlRoutingHandler,                   System.Web, Version=4.0.0.0,                   Culture=neutral,                   PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Abstractions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.WindowsAzure.Diagnostics" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.2.0.0" newVersion="2.2.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="host" userName="username" password="password" />
      </smtp>
    </mailSettings>
  </system.net>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="2147483644" />
      </webServices>
    </scripting>
  </system.web.extensions>
  <dataCacheClients>
    <dataCacheClient name="default">                
      <autoDiscover isEnabled="true" identifier="sub2o" />
      <localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />        
    </dataCacheClient>    
  </dataCacheClients>
  <cacheDiagnostics>
    <crashDump dumpLevel="Off" dumpStorageQuotaInMB="100" />
  </cacheDiagnostics>
</configuration>

ServiceConfiguration.Cloud.cscfg

<ServiceConfiguration serviceName="WindowsAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="3" osVersion="*" schemaVersion="2013-10.2.2">
  <Role name="sub2o">
    <Instances count="1" />
    <ConfigurationSettings>
      <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="DefaultEndpointsProtocol=https;AccountName=name;AccountKey=key" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.Enabled" value="true" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountUsername" value="username" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountEncryptedPassword" value="password" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountExpiration" value="2014-09-07T23:59:59.0000000+04:00" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteForwarder.Enabled" value="true" />
      <Setting name="Microsoft.AppInsights.AccountId" value="ID" />
      <Setting name="Microsoft.AppInsights.InstrumentationKey" value="KEY" />
      <Setting name="Microsoft.AppInsights.EnableMonitoring" value="true" />
      <!-- Uncomment the following section if you want to change the Display Name of your application on the Application Insights Portal. (Default is your WebRole Name)-->
      <!--<Setting name="Microsoft.AppInsights.DisplayName" value="Name" />-->
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel" value="1" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.NamedCaches" value="{&quot;caches&quot;:[{&quot;name&quot;:&quot;default&quot;,&quot;policy&quot;:{&quot;eviction&quot;:{&quot;type&quot;:0},&quot;expiration&quot;:{&quot;defaultTTL&quot;:10,&quot;isExpirable&quot;:true,&quot;type&quot;:1},&quot;serverNotification&quot;:{&quot;isEnabled&quot;:false}},&quot;secondaries&quot;:0}]}" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel" value="1" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.CacheSizePercentage" value="30" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ConfigStoreConnectionString" value="DefaultEndpointsProtocol=https;AccountName=name;AccountKey=key" />
    </ConfigurationSettings>
    <Certificates>
      <Certificate name="Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" thumbprint="value" thumbprintAlgorithm="sha1" />
    </Certificates>
  </Role>
</ServiceConfiguration>

ServiceDefinition.csdef中

<?xml version="1.0"?>
<ServiceDefinition name="WindowsAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2013-10.2.2">
  <WebRole name="sub2o" vmsize="Small">
    <Sites>
      <Site name="Web">
        <Bindings>
          <Binding name="Endpoint1" endpointName="Endpoint1" />
        </Bindings>
      </Site>
    </Sites>
    <Endpoints>
      <InputEndpoint name="Endpoint1" protocol="http" port="80" />
    </Endpoints>
    <Imports>
      <Import moduleName="Diagnostics" />
      <Import moduleName="RemoteAccess" />
      <Import moduleName="RemoteForwarder" />
      <Import moduleName="Caching" />
    </Imports>
    <Startup priority="-2">
      <Task commandLine="AppInsightsAgent\UnifiedBootstrap.bat" executionContext="elevated" taskType="background">
      </Task>
      <Task commandLine="Microsoft.WindowsAzure.Caching\ClientPerfCountersInstaller.exe install" executionContext="elevated" taskType="simple" />
    </Startup>
    <ConfigurationSettings>
      <Setting name="Microsoft.AppInsights.AccountId" />
      <Setting name="Microsoft.AppInsights.InstrumentationKey" />
      <Setting name="Microsoft.AppInsights.EnableMonitoring" />
      <!-- Uncomment the following section if you want to change the Display Name of your application on the Application Insights Portal. (Default is your WebRole Name)-->
      <!--<Setting name="Microsoft.AppInsights.DisplayName" />-->
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel" />
    </ConfigurationSettings>
    <LocalResources>
      <LocalStorage name="DiagnosticStore" sizeInMB="20000" cleanOnRoleRecycle="false" />
    </LocalResources>
  </WebRole>
</ServiceDefinition>

1 个答案:

答案 0 :(得分:1)

问题是由SDK 2.2和2.3之间的冲突引起的。只需要从Properties-&gt; Application更新适用于Windows Azure Cloud Service项目的SDK。这么简单。